【问题标题】:python nested list comprehension with all() or any()使用 all() 或 any() 的 python 嵌套列表理解
【发布时间】:2019-11-03 02:51:12
【问题描述】:

我有两个列表,我想在条件中使用 list2 的元素来检查 list1 中的元素。

list1 = ['antxyz', 'bear456', 'catabc', 'dog0xy', 'zebraayc']
list2 = ['cat', 'dog']

我的原始代码是这样工作的:

all('cat' in item or 'dog' in item for item in list2)
True

any('cat' in item or 'dog' in item for item in list1)
True

现在我不想在条件中使用单独的字符串(猫或狗),而是想将这些字符串放在 list2 中,并用它来对 list1 进行条件检查。我怎么做?

到目前为止,我已经创建了一个像这样的嵌套列表,这似乎让我更接近我需要的东西,但我不知道如何将它包含在 all() 或 any() 函数中。

for item2 in list2:
    for item1 in list1:
        if item2 in item1:
            print(item2 + ' found in ' + item1)
        else:
            print(item2 + ' not found in ' + item1)

dog not found in antxyz
dog not found in bear456
dog not found in catabc
dog found in dog0xy
dog not found in zebraayc
cat not found in antxyz
cat not found in bear456
cat found in catabc
cat not found in dog0xy
cat not found in zebraayc

【问题讨论】:

    标签: python-3.x


    【解决方案1】:
    for item2 in list2:
        for item1 in list1:
            if item2 in item1:
                print(item2 + ' found in ' + item1)
            else:
                print(item2 + ' not found in ' + item1)`
    

    您可以进一步减少它,而不是使用嵌套循环。同样为了更快的查找,我们可以将 list1 更改为 set。 所以,这个代码:

    list1 = {'ant', 'bear', 'cat', 'dog', 'zebra'}
    
    for element in list2:
          if element in list1:
                 print('Found!!')
    

    同样是Jab建议的,可以直接使用setsissubset()方法来查看。

    s.issubset(t) 或 s

    根据您的要求,它是:

    list2.issubset(list1)
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 2010-11-21
      • 2015-08-12
      相关资源
      最近更新 更多