【问题标题】:Check if part of a multi-dimensional list is in a seperate muti-dimensional list检查多维列表的一部分是否在单独的多维列表中
【发布时间】:2020-08-03 13:50:47
【问题描述】:

这是一些示例代码。

list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
list2 = [['three','b'],['four','a'],['five','b']]

for l in list1:
    if l not in list2:
        print(l[0])

以及这段代码的输出。

one
two
three

因为 ['four','a'] 确实出现在两个列表中。

我要做的是检查第一个列表中每个条目的第一项是否仅出现在第二个列表中,我尝试了以下变体

list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
list2 = [['three','b'],['four','a'],['five','b']]

for l in list1:
    if l[0] not in list2:
        print(l[0])

但是,该代码返回

one
two
three
four

虽然“三”和“四”都出现在第二个列表中。

我以前使用过不同的方法来查找仅出现在一对列表中的一个中的值,然后用它来制作一个包含所有可能值且没有重复的主列表,我相信同样应该可以使用这种方法,但语法对我来说是个谜。我哪里错了?

【问题讨论】:

    标签: python list for-loop multidimensional-array syntax


    【解决方案1】:

    您可以使用not any(),然后在理解中检查具体要求:

    list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
    list2 = [['three','b'],['four','a'],['five','b']]
    
    for l in list1:
        if not any(l[0] == l2[0] for l2 in list2):
            print(l[0])
    
    # one
    # two
    

    如果顺序无关紧要,您也可以使用集合:

    list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
    list2 = [['three','b'],['four','a'],['five','b']]
    
    set(l[0] for l in list1) - set(l2[0] for l2 in list2)
    # {'one', 'two'}
    

    【讨论】:

      【解决方案2】:

      你可以使用set operations

      list1 = [['one','a'],['two','a'],['three','a'],['four','a']]
      list2 = [['three','b'],['four','a'],['five','b']]
      
      result = set(i[0] for i in list1) - set(i[0] for i in list2)
      
      print(result)
      
      # output {'one', 'two'}
      

      【讨论】:

        猜你喜欢
        • 2013-04-05
        • 2019-04-08
        • 2014-03-26
        • 2022-11-21
        • 2012-04-04
        • 1970-01-01
        • 2021-12-31
        • 2019-07-11
        • 1970-01-01
        相关资源
        最近更新 更多