Python if 字符串列表上的语句以及关键字的可取/排除列表上的任何语句
Python if statement on list of strings with any statements on desirable / exclusion lists of keywords
我正在尝试检查字符串项列表是否有子字符串属于字符串列表(理想列表)但不属于另一个字符串列表(排除列表)。以下是我正在尝试做的示例:
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
的物品)并且我有一个很难生成包含两个 any
语句的 if 语句条件
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))
但这不起作用。
大功告成,需要确认礼物不在黑名单中(all
& not int
)
wishlist = ['dog', 'cat', 'horse', 'poney']
blocklist = ['bulldog', 'caterpillar', 'workhorse']
gifts = ['a dog', 'a bulldog', 'a cartload of cats', 'Mickey doghouse', 'blob fish']
worthwhile_gifts = []
for gift in gifts:
if any(i in gift for i in wishlist) and all(i not in gift for i in blocklist):
worthwhile_gifts.append(gift)
print(worthwhile_gifts)
结果:
['a dog', 'a cartload of cats', 'Mickey doghouse']
我正在尝试检查字符串项列表是否有子字符串属于字符串列表(理想列表)但不属于另一个字符串列表(排除列表)。以下是我正在尝试做的示例:
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
的物品)并且我有一个很难生成包含两个 any
语句的 if 语句条件
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))
但这不起作用。
大功告成,需要确认礼物不在黑名单中(all
& not int
)
wishlist = ['dog', 'cat', 'horse', 'poney']
blocklist = ['bulldog', 'caterpillar', 'workhorse']
gifts = ['a dog', 'a bulldog', 'a cartload of cats', 'Mickey doghouse', 'blob fish']
worthwhile_gifts = []
for gift in gifts:
if any(i in gift for i in wishlist) and all(i not in gift for i in blocklist):
worthwhile_gifts.append(gift)
print(worthwhile_gifts)
结果:
['a dog', 'a cartload of cats', 'Mickey doghouse']