Python if语句中or运算符判断字符串包含失效问题咨询
问题原因
你写的or用法不符合Python的执行逻辑,所以没有达到预期效果:
- Python中
or是短路运算符,会对左右两侧的表达式依次做布尔求值,遇到第一个布尔值为真的结果就直接返回,不再执行后续判断 - 非空字符串在Python中的布尔值为
True,因此表达式'Ashland Wheat HessianFly' or 'HF_Ashland'永远只会返回第一个字符串'Ashland Wheat HessianFly',第二个关键词根本没有传入匹配逻辑 - 你原代码中的判断条件等价于永远只检查文件名是否包含
'Ashland Wheat HessianFly',自然无法匹配到命名带HF_Ashland的文件 - 额外说明:
__contains__是Python的底层魔法方法,日常写代码不需要直接调用,判断字符串/序列包含关系直接用in关键字即可,可读性和规范性更好。
正确实现
不需要写两次循环遍历文件列表,只要把两个独立的匹配判断用or连接,一次遍历就能完成两类文件的收集:
listCount = 0 while listCount < listSize: file_name = currentDirList[listCount] # 两个完整的包含判断用or连接,才是“满足任一条件即命中”的逻辑 if 'Ashland Wheat HessianFly' in file_name or 'HF_Ashland' in file_name: tifPath = str(Path(dataSource) / file_name) currentSource.append(glob.glob(f"{tifPath}/*.tif")) listCount += 1
如果后续需要新增更多匹配关键词,还可以用any()函数简化写法,不需要堆很长的or判断:
# 所有需要匹配的关键词存在元组里,后续增删直接改这里就行 match_keywords = ("Ashland Wheat HessianFly", "HF_Ashland") listCount = 0 while listCount < listSize: file_name = currentDirList[listCount] if any(key in file_name for key in match_keywords): tifPath = str(Path(dataSource) / file_name) currentSource.append(glob.glob(f"{tifPath}/*.tif")) listCount += 1
更简洁的遍历方式是直接用for循环迭代列表,不需要手动维护计数索引,能避免很多索引计数相关的bug:
match_keywords = ("Ashland Wheat HessianFly", "HF_Ashland") for file_name in currentDirList: if any(key in file_name for key in match_keywords): tifPath = str(Path(dataSource) / file_name) currentSource.append(glob.glob(f"{tifPath}/*.tif"))
内容的提问来源于stack exchange,提问作者Luke C
相关产品推荐
相关产品推荐

