Python中for循环内if结合‘not in’的计数逻辑问题
解决统计完全不包含指定单词的句子数量问题
问题分析
你的代码逻辑错误在于:对每个句子中的每个不匹配单词都单独计数一次,而非判断整个句子是否完全不包含目标单词列表中的任何单词。比如一个完全不匹配的句子会被重复计数8次(对应words列表的长度),最终导致结果远大于预期。
修正方案
方法1:使用标记变量逐句判断
遍历每个句子时,先默认它符合“无目标单词”的条件,再逐个检查目标单词。一旦发现匹配的单词,立即标记该句子不符合条件并终止当前检查,最后根据标记决定是否计数:
sentences = [ "Wow, what a great day today!! #sunshine", "I feel sad about the things going on around us. #covid19", "This is a really nice song. #linkinpark", "The python programming language is useful for data science", "Why do bad things happen to me?", "Apple announces the release of the new iPhone 12. Fans are excited.", "Spent my day with family!! #happy", ] words = ['great', 'excited', 'happy', 'nice', 'wonderful', 'amazing', 'good', 'best'] counter = 0 for sentence in sentences: has_no_target = True for word in words: if word in sentence: has_no_target = False break # 找到匹配后无需继续检查 if has_no_target: counter += 1 print(counter) # 输出3,符合预期
方法2:用any()函数简化逻辑
利用Python内置的any()函数快速判断句子中是否存在任意目标单词,取反后即可得到“完全不包含”的条件,代码更简洁:
sentences = [ "Wow, what a great day today!! #sunshine", "I feel sad about the things going on around us. #covid19", "This is a really nice song. #linkinpark", "The python programming language is useful for data science", "Why do bad things happen to me?", "Apple announces the release of the new iPhone 12. Fans are excited.", "Spent my day with family!! #happy", ] words = ['great', 'excited', 'happy', 'nice', 'wonderful', 'amazing', 'good', 'best'] counter = sum(1 for sentence in sentences if not any(word in sentence for word in words)) print(counter) # 输出3
内容的提问来源于stack exchange,提问作者nosni khoritz
相关产品推荐
相关产品推荐

