You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python查找列表中字符串子串索引失败问题求助

问题诊断与解决

你的findMatches函数返回空列表,核心问题是判断条件错误:

  • str.find()方法在子串位于字符串开头时返回0,不存在时返回-1。你写的if listElement.find(s) > 0会漏掉子串在开头的匹配项,甚至当子串完全等于列表元素时也会被忽略。

修正后的函数

把判断条件改成检查find()的结果不等于-1即可:

def findMatches(s, l1):
    matched_indexes = []
    i = 0
    length = len(l1)

    while i < length:
        listElement = l1[i]
        # 只要子串存在就加入索引
        if listElement.find(s) != -1:
            matched_indexes.append(i)
        i += 1
    return matched_indexes

更简洁的Pythonic写法

用enumerate可以直接遍历索引和元素,代码更简洁高效:

def findMatches(s, l1):
    return [index for index, elem in enumerate(l1) if s in elem]

补充说明

你原本用的list.count(filename)和list.index(filename)都是完全匹配逻辑,和你需要的子串匹配不是同一回事。比如列表元素是"test_file.txt"、目标是"test"时,count和index都找不到匹配,但子串匹配应该能正确识别。

内容的提问来源于stack exchange,提问作者Matthias Pospiech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:24:52