如何获取 python 中两个嵌套列表的每个元素的交集?

How to get intersection of each element of two nested lists in python?

我在 pyspark 环境中工作,如果我有 两个嵌套列表 a 和 b,

a=[[1,2,3],[8,9,45,0,65],[3,7,23,88],[44,77,99,100,654]]
b=[[1,3,7],[0,9,67,22,45,8,11],[23,3],[100]]

我想要这两个的交集在python

intersection_list=[[1,3],[8,9,45,0],[3,23],[100]]

最后的计数是

list_count=[2,3,2,1]

如何在 pyspark 中得到这个结果?

我试过了

[[[n for n in a if n in b]for x in a]for y in b]

但这并没有给我所需的 intersection_list

有没有办法在 pypark 中使用 rdd 做到这一点?

[[n for n in x if n in y] for x, y in zip(a, b)]

然而,如果子列表很大,这样会更好:

[set(x).intersection(y) for x, y in zip(a, b)]

(虽然元素的顺序丢失了)

a=[[1,2,3],[8,9,45,0,65],[3,7,23,88],[44,77,99,100,654]]
b=[[1,3,7],[0,9,67,22,45,8,11],[23,3],[100]]

intersection_list = [list(set(x) & set(y)) for x, y in zip(a,b)]

>> [[1, 3], [8, 9, 45, 0], [3, 23], [100]]

list_count = [ len(x) for x in intersection_list ]

>> [2, 4, 2, 1]