你如何在两个不同的二维列表中比较和 return 重复项?

How do you compare and return duplicates in two different 2d list?

我想 return 两个不同的二维列表中的重复项。但是我无法弄清楚要编写什么代码。例如,我希望变量 "a" 与变量 "b" 和 return 的副本进行比较。下面是我的两个二维列表。

a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]

我希望我的结果是:

c = [[2,3,6,8],[15,17,21,22]]

这应该有效,它应该让你开始 -

import itertools

#Input lists
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]

#Take a product of both the lists ( a X b )
z = itertools.product(a,b)

#Uncomment the following to see what itertools.product does
#[i for i in z]

#Return only the elements which the pair of the same element repeats (using string match)
[i[0] for i in z if str(i[0])==str(i[1])]

[[2, 3, 6, 8], [15, 17, 21, 22]]

您只需要检查 a 中的列表是否也在 b 中。

a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
c=[]
for i in a:
    if i in b:
        c.append(i)
print(c)

输出:

[[2, 3, 6, 8], [15, 17, 21, 22]]

试试这个:

a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
c = []
for i in a + b: 
    if (a + b).count(i) > 1 and i not in c:
        c.append(i)

@mulaixi 的答案是可以的,但是在输出列表中你可能会看到重复的。

一种线性列表理解方法:

dups = [i for i in a if i in b]

输出:

[[2, 3, 6, 8], [15, 17, 21, 22]]