Python中if...or...条件不符合预期的原因咨询
问题原因分析
你的核心问题是逻辑运算符用反了,把需要的and写成了or,完全搞反了判断逻辑。
你原本的需求是:只处理既不包含"channel",也不包含"eof"的行。也就是说必须同时满足两个排除条件:
- 行内没有"channel"
- 行内没有"eof"
但你写的if "channel" not in sample or "eof" not in sample,逻辑变成了「只要满足其中一个条件就执行后续代码」:
- 对于带"channel"的行,虽然第一个条件不成立,但第二个条件("eof"不在行内)是成立的,所以
or整体为真,会尝试把"channel 00"转成float,直接触发报错。 - 对于"eof"行,第一个条件("channel"不在行内)成立,
or整体为真,同样会触发转换报错。
正确写法
你可以用两种方式修正条件:
- 用
and同时判断两个排除条件:
log = open("mq_test.txt", 'r') data = [] for count, sample in enumerate(log): if "channel" not in sample and "eof" not in sample: data.append(float(sample)) print(count) log.close()
- 用
not包裹需要排除的情况:
log = open("mq_test.txt", 'r') data = [] for count, sample in enumerate(log): if not ("channel" in sample or "eof" in sample): data.append(float(sample)) print(count) log.close()
额外优化建议
处理文件时推荐用with语句,它会自动帮你关闭文件,避免手动关闭遗漏的问题:
data = [] with open("mq_test.txt", 'r') as log: for count, sample in enumerate(log): if "channel" not in sample and "eof" not in sample: data.append(float(sample)) print(count)
内容的提问来源于stack exchange,提问作者DrBwts
相关产品推荐
相关产品推荐

