【问题标题】:Python if statement on list of strings with any statements on desirable / exclusion lists of keywordsPython if 对字符串列表的语句以及对期望/排除关键字列表的任何语句
【发布时间】: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


    【解决方案1】:

    你已经接近了,你需要检查礼物不在黑名单中(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']
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 2012-09-04
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多