[英]Combinations from multiple sets where each result has only one element from each set
So I have some sets:所以我有一些套装:
sets = [
{a1,a2}, #a set
{b1,b2}, #b set
{c1,c2}, #c set
...
]
And I need to get all possible combinations of all sizes... but only one element from each set.而且我需要获得所有尺寸的所有可能组合......但每组只有一个元素。
[
{a1}, {b1}, ..., # all single
{a1, b1}, {a1, b2} ..., # all pairs
... # all combinations less than n
{a1,b1,c1 ... }, {a2,b1,c1 ... }, ..., # size n
]
At the moment I am using iter_tools' powerset on the union of all the sets then filtering, but this is incredibly slow when the sets get large.目前我在所有集合的并集上使用 iter_tools 的 powerset 然后过滤,但是当集合变大时,这非常慢。
large_set = union_all_sets(sets)
r = more_itertools.powerset(large_set)
r = filter_1(r)
I was wondering if there is a simple function for this that I don't know the name of?我想知道是否有一个我不知道名字的简单 function ? Or if anybody had any suggestions how I can avoid calling powerset on the large set?或者,如果有人对我如何避免在大型设备上调用 powerset 有任何建议?
You can build combinations of 1, then 2... n of your sets, and for each of these combinations, generate the cartesian product:您可以构建 1,然后 2... n 的集合的组合,并且对于这些组合中的每一个,生成笛卡尔积:
from itertools import product, combinations
sets = [
{"a1", "a2"}, #a set
{"b1", "b2"}, #b set
{"c1", "c2", "c3"} #c set
]
out = []
for size in range(1, len(sets)+1):
for combination in combinations(sets, r=size):
out.extend(set(p) for p in product(*combination))
print(out)
Output: Output:
[{'a2'}, {'a1'}, {'b1'}, {'b2'}, {'c2'}, {'c1'}, {'c3'},
{'b1', 'a2'}, {'b2', 'a2'}, {'b1', 'a1'}, {'b2', 'a1'}, {'c2', 'a2'},
{'c1', 'a2'}, {'c3', 'a2'}, {'c2', 'a1'}, {'c1', 'a1'}, {'c3', 'a1'},
{'b1', 'c2'}, {'b1', 'c1'}, {'b1', 'c3'}, {'c2', 'b2'}, {'c1', 'b2'},
{'b2', 'c3'},
{'b1', 'c2', 'a2'}, {'b1', 'c1', 'a2'}, {'b1', 'c3', 'a2'}, {'c2', 'b2', 'a2'},
{'c1', 'b2', 'a2'}, {'b2', 'c3', 'a2'}, {'b1', 'c2', 'a1'}, {'b1', 'c1', 'a1'},
{'b1', 'c3', 'a1'}, {'c2', 'b2', 'a1'}, {'c1', 'b2', 'a1'}, {'b2', 'c3', 'a1'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.