检查是否不在列表中 - 在Python多个条件

问题描述 投票:4回答:2

我有不固定数量的项目,E两个列表。 G。:

data=['sun','stars','moon','supermoon','planet','comet','galaxy']

forbidden=['mo','st','lax']

我需要打印只不包含任何data列出的字符串的那些forbidden的项目。在这种情况下,输出会

sun
planet
comet

我试过是

print [x for x in data if forbidden not in x ]

这仅适用于一个条件(在forbidden列表中的一个项目)

有什么办法如何检查所有条件在一次?

如果我知道在forbidden我可以使用的项目数

print [x for x in data if forbidden[0] not in x and forbidden[1] not in x]

但它不与未知数量的项目工作。

谢谢你的帮助。

python python-3.x list
2个回答
5
投票

您可以使用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']

2
投票

这里更多的是一种功能性做法:

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

编辑:如果数据很大,这将更加妥善地处理它,并更快地返回结果

© www.soinside.com 2019 - 2024. All rights reserved.