如果列表中不包含项,则Python列表理解
我有一个字符串列表,我想找到不包含给定单词字母的字符串。使用列表理解,我可以很容易地找到与给定单词匹配的项目。我很难扭转这个过程如果列表中不包含项,则Python列表理解,python,list,list-comprehension,Python,List,List Comprehension,我有一个字符串列表,我想找到不包含给定单词字母的字符串。使用列表理解,我可以很容易地找到与给定单词匹配的项目。我很难扭转这个过程 import sys userin = sys.argv[1] word = userin.lower() cars = ['mercedes', 'bmw', 'ford', 'renault'] result = [] check = set(word) result = [c for c in cars if any(l in check for l in
import sys
userin = sys.argv[1]
word = userin.lower()
cars = ['mercedes', 'bmw', 'ford', 'renault']
result = []
check = set(word)
result = [c for c in cars if any(l in check for l in c)]
print result
我认为这可以通过以下方式逆转:
result = [c for c in cars if not(l in check for l in c)]
但这并没有给出我想要的结果。
如果您有任何建议,我将不胜感激。我认为
不
不会像您认为的那样做。您实际确定的内容如下:
not(generator expression)
这与:
bool(generator expression)
生成器的布尔值总是简单的“True”,因为它是一个非None
python对象,并且它们在默认情况下是真实的,除非应用一些特殊的逻辑(例如空容器,等于0
,或者是False
对象)。因此,代码的这一部分只是无条件地返回False
你真正的意思是:
result = [c for c in cars if not any(l in check for l in c)]
但在这种情况下,使用set
方法会更好:
result = [c for c in cars if not check.intersection(c)]
要反转,我想只需使用旧的if(_;)=False 对此
result = [c for c in cars if any(l in check for l in c) == False]
希望这能帮助男人不太确定这是否是你需要的
编辑:
你也可以做一个not any()为什么不使用设置差异呢?
any(l在c中检查l)
的反面是not any(l在c中检查l)
你有没有尝试过结果=[c在汽车中如果没有任何(l在c中检查l在c中)]
?当你做设置(“abc”)
,你会得到设置(['a',c',b']
-这可能是您出现问题的原因。要进行调试,请使用pdb或print语句查看局部变量的计算结果。是的,您是对的。非常感谢你的帮助。
result = [c for c in cars if any(l in check for l in c) == False]