简体   繁体   English

如果列表中未包含项目,则使用Python列表理解

[英]Python list comprehension if item is not included in list

I have a list of strings and I'd like to find the strings that do not contain letters of a given word. 我有一个字符串列表,我想找到不包含给定单词字母的字符串。 I can easily find the items that do match the given word using list comprehension. 我可以使用列表推导轻松找到与给定单词匹配的项目。 I am having trouble reversing this process. 我在逆转此过程时遇到了麻烦。

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

I thought this could be reversed using: 我认为可以使用以下方法将其逆转:

result = [c for c in cars if not(l in check for l in c)]

But that does not give the output I'm looking for. 但这并不能提供我想要的输出。 I'd be very grateful for any suggestions. 如有任何建议,我将不胜感激。

I think not does not do what you think it does there. 我认为not按照您认为的那样做。 What you are actually determining is as follows: 您实际确定的内容如下:

not(generator expression)

Which is the opposite of: 与之相反:

bool(generator expression)

The boolean value of a generator is always simply 'True' as it's a non- None python object, and they are truthy by default unless some special logic applies (such as an empty container, equaling 0 , or being the False object). 生成器的布尔值始终是“ True”,因为它是一个非None python对象,默认情况下它们是真实的,除非应用某些特殊逻辑(例如,空容器,等于0或为False对象)。 Thus that part of your code simply returns False unconditionally. 因此,您的那部分代码只是无条件地返回False

What you actually meant is this: 您的实际意思是:

result = [c for c in cars if not any(l in check for l in c)]

But in this case you would be better served by using set methods: 但是在这种情况下,使用set方法更好:

result = [c for c in cars if not check.intersection(c)]

To reverse I guess just use the age old if(__) == False 要扭转,我猜只是使用旧的if(__)== False

result = [c for c in cars if not(l in check for l in c)]

to this 对此

result = [c for c in cars if any(l in check for l in c) == False]

Hope this helps man not too sure if thats whacha need 希望这可以帮助男人不太确定那是否需要

Edit: you can also do a not any() 编辑:您也可以执行not any()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM