【发布时间】:2020-07-19 17:15:13
【问题描述】:
我正在尝试检查字符串项目列表是否有子字符串属于字符串列表(理想列表)但不属于另一个字符串列表(排除列表)。下面是我正在尝试做的一个示例:
worthwhile_gifts = []
wishlist = ['dog', 'cat', 'horse', 'pony']
gifts = ['a dog', 'a bulldog', 'a cartload of cats', 'Mickey doghouse', 'blob fish']
# Checking that various Xmas gifts include items from wishlist
for gift in gifts:
if any(i in gift for i in wishlist):
worthwhile_gifts.append(gift)
查看结果,我们得到了我们期望的结果
>>> print(worthwhile_gifts)
['a dog', 'a bulldog', 'a cartload of cats', 'Mickey doghouse']
现在我要做的是根据以下两个列表检查礼物列表(我想要来自 wishlist 但不是来自 blocklist 的项目)并且我很难生成 if 语句包含两个 any 语句的条件
wishlist = ['dog', 'cat', 'horse', 'poney']
blocklist = ['bulldog', 'caterpillar', 'workhorse']
# Expected result would exclude 'bulldog'
>>> print(worthwhile_gifts)
['a dog', 'a cartload of cats', 'Mickey doghouse']
知道如何构造这个 if 语句吗?我试过if (any(i in gift for i in wishlist)) and (any(i in gift for i not in blocklist)),但这不起作用。
【问题讨论】:
标签: python list if-statement any