检查多维列表的一部分是否在单独的多维列表中

问题描述 投票:0回答:2

您好,谢谢您的阅读。

这里是一些示例代码。

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
2个回答
0
投票

您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.