繁体   English   中英

如何返回n个不同列表的所有可能组合的交集

[英]how to return the intersection of all possible combinations of n different lists

我想知道是否有一种算法可以返回 n 个不同列表的所有可能组合的交集。 我的示例如下,其中 n = 3 个不同的列表:

list1 = [1,2,3,4,5]
list2 = [1,3,5]
list3 = [1,2,5]

结果应如下所示:

list1_2_intersection = [1,3,5]
list1_3_intersection = [1,2,5]
list2_3_intersection = [1,5]
list1_2_3_intersection = [1,5]

我正在考虑首先使用combination来获取 n 个集合的所有可能组合,并使用它手动使用intersection创建交叉点。 但是,由于我有 6 个不同的集合,这似乎非常耗时,这就是为什么我想知道是否有更有效的方法来计算它。 提前致谢: :)

如果你有一个列表中的所有集合,你可以使用itertools itertools 的more-itertools -package ( pip install more-itertools ),使用more_itertools.powerset来获取这些元素的所有组合,就像在这篇文章中所做的那样.

然后得到交集就是你自己指出的使用set.intersection的问题。 所以解决方案看起来像这样

from more_itertools import powerset

sets = [{1,2,3,4,5},{1,3,5},{1,2,5}]
pwset = powerset(sets)
res = [c[0].intersection(*c[1:]) if len(c)>1 else c for c in pwset]

如果您只是在列表等可迭代对象中加载或定义集合:

my_sets = [
    {1, 2, 3, 4, 5},
    {1, 3, 5},
    {1, 2, 5}
]

my_set_intersection = set.intersection(*my_sets)
print(my_set_intersection)

当然, print只是为了显示结果,在my_set_intersection

如果你只有几套:

set1 = {1, 2, 3, 4, 5},
set2 = {1, 3, 5},
set3 = {1, 2, 5}

intersection_123 = set1 & set2 & set3
# or:
intersection_123 = set.intersection(set1, set2, set3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM