【问题标题】:How to check if all keys are present in list of lists element in python如何检查python中列表元素列表中是否存在所有键
【发布时间】:2021-11-15 23:28:38
【问题描述】:

假设有一个列表列表。如何循环遍历列表的第二个元素并检查其他列表中的所有元素是否都存在?

list = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [ 2, 5, 9]


if all (item in list for item[1] in required):
    log.debug('all items exist in nested list') //<- this should be printed

item[1] 在示例中是错误的,我不知道如何更改它。

【问题讨论】:

  • 这里的item 是什么?迭代变量还是其他?
  • @AmberBhanarkar 是的,它是一个迭代变量,目的是遍历列表的每个元素。

标签: python-3.x list loops


【解决方案1】:

带套

lst_set = set(x[1] for x in lst)
required=set(required)
print(lst_set&required==required)

【讨论】:

    【解决方案2】:

    试试这个:

    lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
    required = [ 2, 5, 9]
    
    chk = [any(map(lambda x: r in x, lst)) for r in required]
    # [True, True, True]
    
    if all(chk):
        print('all items exist in nested list')
    

    用另一个required list测试:

    lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
    required = [ 2, 5, 11]
    
    [any(map(lambda x: r in x, lst)) for r in required]
    # [True, True, False]
    

    【讨论】:

    • 这行得通。非常感谢!
    【解决方案3】:
    lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
    required = [2, 5, 9]
    
    checker = set()
    
    for sublist in lst:
        for elem in sublist:
            if elem in required:
                checker.add(elem)
    
    if set(required) == checker:
        log.debug('all items exist in nested list')
    

    【讨论】:

      猜你喜欢
      • 2012-04-03
      • 2013-08-07
      • 2021-12-17
      • 1970-01-01
      • 2019-10-04
      • 2011-08-02
      • 2018-01-10
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多