Python -一次取两个的多个列表的交集



在python中,我能够得到多个列表的交集:

arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
result = set.intersection(*map(set, arr))

输出:

result = {3}

现在,我想要的结果是所有3个嵌套列表的交集,一次取2个:

result = {2, 3, 4}

as[2,3]在第一和第二列表之间常见,[3,4]在第二和第三列表之间常见,[3]在第一和第三列表之间常见。

是否有一个内置的功能?

可以取所有交点对的并集,如下所示:

import itertools as it
arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
res = set.union(*(set(i).intersection(set(j)) for i,j in it.combinations(arr,2)))
# output {2, 3, 4}

*根据@DanielHao的评论编辑

尝试itertools.combinations

from itertools import combinations
arr = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
result = [set.intersection(*map(set, i)) for i in combinations(arr,2)] 
# print(list(combinations(arr,2)) to get the combinations
# [{2, 3}, {3}, {3, 4}]

最新更新