简体   繁体   English

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

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

I was wondering if there is an algorithm that can return the intersection of all possible combinations of n different lists.我想知道是否有一种算法可以返回 n 个不同列表的所有可能组合的交集。 My example is the following with n = 3 different lists:我的示例如下,其中 n = 3 个不同的列表:

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

the outcome should look like this:结果应如下所示:

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

I was thinking to first use combination to get all possible combinations of n sets and use that to create intersections using intersection manually.我正在考虑首先使用combination来获取 n 个集合的所有可能组合,并使用它手动使用intersection创建交叉点。 However, since I have 6 different sets this seems very time consuming, which is why I was wondering if there is a more efficient way to compute this.但是,由于我有 6 个不同的集合,这似乎非常耗时,这就是为什么我想知道是否有更有效的方法来计算它。 Thanks in advance: :)提前致谢: :)

If you have all sets in a list, you can use the more-itertools -package ( pip install more-itertools ), which is based on itertools , to get all combinations of those elements using more_itertools.powerset , as is done in this post .如果你有一个列表中的所有集合,你可以使用itertools itertools 的more-itertools -package ( pip install more-itertools ),使用more_itertools.powerset来获取这些元素的所有组合,就像在这篇文章中所做的那样.

Then getting the intersection is a matter of using set.intersection as you point out yourself.然后得到交集就是你自己指出的使用set.intersection的问题。 So a solution can look like this所以解决方案看起来像这样

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]

If you just load or define the sets in an iterable like a list:如果您只是在列表等可迭代对象中加载或定义集合:

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

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

Of course, the print is just there to show the result, which is in my_set_intersection当然, print只是为了显示结果,在my_set_intersection

If you just have a couple of sets:如果你只有几套:

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