簡體   English   中英

Python - 一次取兩個列表的交集

[英]Python - Intersection of multiple lists taken two at a time

在 python 中,我能夠得到多個列表的交集:

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

Output:

result = {3}

現在,我希望結果是一次取 2 個的所有 3 個嵌套列表的交集:

result = {2, 3, 4}

由於 [2, 3] 在第一個和第二個列表之間是通用的,[3, 4] 在第二個和第三個列表之間是通用的,[3] 在第一個和第三個列表之間是通用的。

有內置的 function 嗎?

您可以按以下方式獲取所有交叉點對的並集;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM