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
相关产品推荐
相关产品推荐

