一尘不染

Python-查找两个嵌套列表的交集?

python

我知道如何得到两个平面列表的交集:

b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
要么

def intersect(a, b):
    return list(set(a) & set(b))

print intersect(b1, b2)

但是当我必须找到嵌套列表的交集时,我的问题就开始了:

c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

最后,我希望收到:

c3 = [[13,32],[7,13,28],[1,6]]

你们能帮我这个忙吗?


阅读 479

收藏
2020-02-14

共2个答案

一尘不染

如果你想:

c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [[13, 32], [7, 13, 28], [1,6]]

然后这是你的Python 2解决方案:

c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]

在Python 3 filter返回一个迭代,而不是list,所以你需要用filter与呼叫list():

c3 = [list(filter(lambda x: x in c1, sublist)) for sublist in c2]

说明:

过滤器部分接受每个子列表的项目,并检查它是否在源列表c1中。对c2中的每个子列表执行列表推导。

2020-02-14
一尘不染

你不需要定义交集。它已经是场景的一流组成部分。

>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])
2020-02-14