Itertools.product 自定义每个输入的组合数量?

Itertools.product to customize the amount of combos for each input?

我正在使用 itertools.product 想出一个组合 groups.I 我不擅长没有例子的解释,所以这里的代码是这样的。

group1=[1,2,3];group2=[4,5,6];group3=[7,8,9]
list(itertools.product(group1,group2,group3))

这给出了每组 1 的所有组合。但是我将如何获得第 1 组的 2 个数字、第 2 组的 2 个数字和第 3 组的 1 个数字的组合?

例如,我希望组合 (1,2,5,6,9) 出现在列表中。可以自定义吗? itertools.product 似乎没有我需要的那么灵活,而且我一直未能成功学习笛卡尔积以了解如何调整 .product 函数。

编辑:为了简单起见,我将组缩小了,但每个组都有数百个唯一值。

取每组 r 组合的笛卡尔积:

from itertools import product, chain, combinations, permutations

groups = [[1,2,3],[4,5,6],[7,8,9]]
counts = (2, 2, 1)

selections = [combinations(g, c) for g, c in zip(groups, counts)]

for n_tuple in product(*selections):
    print(tuple(chain.from_iterable(n_tuple)))

输出:

(1, 2, 4, 5, 7)
(1, 2, 4, 5, 8)
(1, 2, 4, 5, 9)
(1, 2, 4, 6, 7)
(1, 2, 4, 6, 8)
(1, 2, 4, 6, 9)
(1, 2, 5, 6, 7)
(1, 2, 5, 6, 8)
(1, 2, 5, 6, 9)
(1, 3, 4, 5, 7)
(1, 3, 4, 5, 8)
(1, 3, 4, 5, 9)
(1, 3, 4, 6, 7)
(1, 3, 4, 6, 8)
(1, 3, 4, 6, 9)
(1, 3, 5, 6, 7)
(1, 3, 5, 6, 8)
(1, 3, 5, 6, 9)
(2, 3, 4, 5, 7)
(2, 3, 4, 5, 8)
(2, 3, 4, 5, 9)
(2, 3, 4, 6, 7)
(2, 3, 4, 6, 8)
(2, 3, 4, 6, 9)
(2, 3, 5, 6, 7)
(2, 3, 5, 6, 8)
(2, 3, 5, 6, 9)

如果从每个组中选择时顺序很重要(例如,如果 (3, 2, 5, 6, 9)(2, 3, 5, 6, 9) 不同),您可以将 combinations 更改为 permutations

您应该注意到,这会从 N 个组中生成 choose(|g1|, c1) * choose(|g2|, c2) * ... * choose(|gN|, cN) 个元素,其中 choose(n, k)binomial coefficient。如果您的小组规模如您所说的那样是数百人,或者如果小组的数量也很大,这将是无法估量的大。