如何比较和返回两个不同的2d列表中的重复项?

时间:2019-10-19 18:30:35

标签: python python-3.x multidimensional-array 2d

我想在两个不同的2d列表中返回重复项。但是我很难弄清楚要写什么代码。例如,我希望变量“ 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 = [[2,3,6,8],[15,17,21,22]]

4 个答案:

答案 0 :(得分:0)

这应该可行,它应该可以让您入门-

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]]

答案 1 :(得分:0)

您只需要检查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]]

答案 2 :(得分:0)

尝试一下:

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的回答还可以,但是在输出列表中您可能会看到重复的内容。

答案 3 :(得分:0)

一种班轮名单理解方法:

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

输出:

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