检查是否不在列表中-Python中的更多条件
我有两个列表,没有固定数量的项目,例如。g、 :检查是否不在列表中-Python中的更多条件,python,python-3.x,list,Python,Python 3.x,List,我有两个列表,没有固定数量的项目,例如。g、 : data=['sun','stars','moon','supermoon','planet','comet','galaxy'] forbidden=['mo','st','lax'] 我只需要打印数据中不包含禁止中列出的任何字符串的项目。在这种情况下,输出将是 sun planet comet 我试过的是 print [x for x in data if forbidden not in x ] 仅适用于一种情况(禁止列表中的一项)
data=['sun','stars','moon','supermoon','planet','comet','galaxy']
forbidden=['mo','st','lax']
我只需要打印数据
中不包含禁止
中列出的任何字符串的项目。在这种情况下,输出将是
sun
planet
comet
我试过的是
print [x for x in data if forbidden not in x ]
仅适用于一种情况(禁止列表中的一项)
有没有办法一次检查所有情况
如果我知道禁止
中的项目数量,我可以使用
print [x for x in data if forbidden[0] not in x and forbidden[1] not in x]
但它不适用于数量未知的项目
谢谢您的帮助。您可以使用
all
:
data=['sun','stars','moon','supermoon','planet','comet','galaxy']
forbidden=['mo','st','lax']
print([i for i in data if all(c not in i for c in forbidden)])
输出:
['sun', 'planet', 'comet']
以下是更多的功能性方法:
from itertools import product
from operator import contains, itemgetter
first = itemgetter(0)
p = product(data, forbidden)
f = filter(lambda tup: contains(*tup), p)
set(data).difference(set(map(first, f)))
{'comet', 'planet', 'sun'} # order is not preserved here if that matters
编辑:如果数据很大,这将更优雅地处理它,并更快地返回结果