【问题标题】:Comparing entries in a list to another list将列表中的条目与另一个列表进行比较
【发布时间】:2021-10-17 19:59:37
【问题描述】:

使用 Python 3.9.5

a=['Apple', 'Orange', 'peaches']

b=[['Lettuce', 'Apple', 'eggs'],['potato', 'tomato', 'pepper']]

我想比较 a 到 b 中的任何值,如果有匹配项,请继续下一个列表( 我的程序生成关键词列表)我想将初始列表“a”与我拥有的列表进行比较,如果有匹配项,则下一步,如果没有匹配项,则执行打印该列表之类的操作。

这是我尝试过的,但不起作用

for i in b:
   if any(x in a for x in [b, c]):
      continue 
   else:
       print(#the current sublist)

我想说的是,对于整数,此代码有效,但对于列表或字符串则无效,感谢反馈

【问题讨论】:

  • 对不起,我的意思是整数列表可以工作,但字符串列表不能。
  • 您应该编辑问题,而不是在评论中发布编辑。

标签: python list generator


【解决方案1】:
a = ['Apple', 'Orange', 'peaches']
b = [['Lettuce', 'Apple', 'eggs'], ['potato', 'tomato', 'pepper']]

for el in b:
    if any([x in a for x in el]):
        print("ok")
    else:
        print(el)

返回:

True
False

说明

  1. 首先我们迭代b,所以我们在第一次迭代时有el = ['Lettuce', 'Apple', 'eggs']
  2. 接下来我们创建布尔列表:[x in a for x in el]。我们检查当前元素el 中是否有a 的元素:[False, True, False] - 对于b 的第一个元素。
  3. 接下来,我们使用 any() 将布尔列表 ([False, True, False]) 减少为一个布尔值

【讨论】:

    【解决方案2】:

    如果我正确理解了问题,那应该可以:

    to_check = ['Apple','Orange','peaches']
    
    list_of_lists = [['Lettuce', 'Apple','eggs'],['potato','tomato','pepper']]
    
    for _list in list_of_lists:
        if any([element_to_check in _list for element_to_check in to_check]):
            print('Matched')
        else:
            print('Not matched')
    

    【讨论】:

      【解决方案3】:

      我不知道你从哪里得到变量c。只需替换此行即可。

      发件人:

      if any(x in a for x in [b,c]):
      

      收件人:

      if any(x in a for x in i):
      

      i 的值是 b 中的每个子列表,例如 ['Lettuce', 'Apple', 'eggs'],因此您的算法会迭代子列表中的每个项目,并检查是否也在 a 中的任何元素。


      这是对您的算法的改进。目前,您的算法以O(z * y * x) 的时间复杂度运行,其中:

      • x = a 的长度
      • y = b 的长度
      • z = b 中每个子列表的平均长度

      不要总是遍历列表a,而是将其设为哈希表,例如设置,这将使搜索从线性O(x) 提高到恒定O(1)

      a_set = set(a)
      
      for i in b:
         if any(x in a_set for x in i):
             # Do something or just continue
            continue 
         else:
             print(i)
      

      这会将时间复杂度提高到O(z * y)。作为比较,如果a 中有 20 个元素,b 中有 10 个元素,b 的每个子列表中平均有 3 个元素,则之前使用列表 a 的算法将运行 3 * 10 * 20 次,总共 600 次迭代,而集合 a 只运行 3 * 10 次,总共 30 次迭代。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多