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

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]

or

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

你们能帮我一下吗?

相关的

在python中扁平一个浅列表


当前回答

python获取两个列表的交集的方法是:

[x for x in list1 if x in list2]

其他回答

运算符&取两个集合的交集。

{1, 2, 3} & {2, 3, 4}
Out[1]: {2, 3}

我们可以使用set方法:

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

   result = [] 
   for li in c2:
       res = set(li) & set(c1)
       result.append(list(res))

   print result
# Problem:  Given c1 and c2:
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]]
# how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?

这里有一种不涉及集合的方法来设置c3:

c3 = []
for sublist in c2:
    c3.append([val for val in c1 if val in sublist])

但如果你喜欢只用一行,你可以这样做:

c3 = [[val for val in c1 if val in sublist]  for sublist in c2]

它是列表推导式中的列表推导式,这有点不寻常,但我认为你应该不会有太多的问题。

python获取两个列表的交集的方法是:

[x for x in list1 if x in list2]

你不需要定义交集。它已经是集合的一流部分了。

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