笛卡尔积,返回不同长度的输出

HuN*_*HuN 1 python list cartesian-product python-itertools python-3.x

所以我有这些清单:

a = [1, 2, 3]
b = [11, 12, 13, 14]
c = [21, 22, 23, 24, 25, 26]
Run Code Online (Sandbox Code Playgroud)

我希望获得所有可能的组合(重复都很好),包括来自的a3个元素b和来自3个元素的2 个元素c.像这样:

([1, 2], [11, 12, 13], [21, 22, 23]) # 1
([1, 2], [11, 12, 13], [22, 23, 24]) # 2
# all the way to...
([2, 3], [12, 13, 14], [24, 25, 26]) # 16
Run Code Online (Sandbox Code Playgroud)

如果我使用itertools.product(),它只给我每个列表1:

import itertools

def cartesian(the_list):
    for i in itertools.product(*the_list):
        yield i

a = [1, 2, 3]
b = [11, 12, 13, 14]
c = [21, 22, 23, 24, 25, 26]

test = cartesian([a, b, c])

print(next(test)) 
# Gives (1, 11, 21). But I need ([1, 2], [11, 12, 13], [21, 22, 23])

print(next(test)) 
# Gives (1, 11, 22). But I need ([1, 2], [11, 12, 13], [22, 23, 24])
Run Code Online (Sandbox Code Playgroud)

我可以使用多个嵌套for循环,但如果我有很多列表,我需要太多循环.

那么我该如何实现一个算法,它给出了所有可能的组合,每个组合由每个输入列表中的一定数量的元素组成?

the*_*eye 5

构建一个生成器函数,它可以生成任意数量的值并在其中使用它product,就像这样

>>> from itertools import product
>>> def get_chunks(items, number=3):
...     for i in range(len(items) - number + 1): 
...         yield items[i: i + number]
...     
... 
Run Code Online (Sandbox Code Playgroud)

然后cartesian像这样定义你的生成器

>>> def cartesian(a, b, c):
...     for items in product(get_chunks(a, 2), get_chunks(b), get_chunks(c)):
...         yield items
...     
... 
Run Code Online (Sandbox Code Playgroud)

如果你使用的是Python 3.3+,你可以yield from在这里使用,就像这样

>>> def cartesian(a, b, c):
...     yield from product(get_chunks(a, 2), get_chunks(b), get_chunks(c))
... 
Run Code Online (Sandbox Code Playgroud)

然后,当你将所有元素作为列表时,你就会得到

>>> from pprint import pprint
>>> pprint(list(cartesian([1, 2, 3],[11, 12, 13, 14],[21, 22, 23, 24, 25, 26])))
[([1, 2], [11, 12, 13], [21, 22, 23]),
 ([1, 2], [11, 12, 13], [22, 23, 24]),
 ([1, 2], [11, 12, 13], [23, 24, 25]),
 ([1, 2], [11, 12, 13], [24, 25, 26]),
 ([1, 2], [12, 13, 14], [21, 22, 23]),
 ([1, 2], [12, 13, 14], [22, 23, 24]),
 ([1, 2], [12, 13, 14], [23, 24, 25]),
 ([1, 2], [12, 13, 14], [24, 25, 26]),
 ([2, 3], [11, 12, 13], [21, 22, 23]),
 ([2, 3], [11, 12, 13], [22, 23, 24]),
 ([2, 3], [11, 12, 13], [23, 24, 25]),
 ([2, 3], [11, 12, 13], [24, 25, 26]),
 ([2, 3], [12, 13, 14], [21, 22, 23]),
 ([2, 3], [12, 13, 14], [22, 23, 24]),
 ([2, 3], [12, 13, 14], [23, 24, 25]),
 ([2, 3], [12, 13, 14], [24, 25, 26])]
Run Code Online (Sandbox Code Playgroud)