列出所有组合

Moo*_*sez -2 python python-itertools

我有一个清单[1,2,3].我想要一个接收列表的函数和另一个数字,即长度.

f([1, 2, 3], 4) = [
[1, 1, 1, 1],
[1, 1 , 1, 2],
[1, 1, 1, 3],
[1, 1, 2, 1],
[1, 1, 3, 1],
#and so on...
]
Run Code Online (Sandbox Code Playgroud)

也许itertools有答案?

Rob*_*obᵩ 6

itertools.combinations_with_replacement 是你寻求的功能.

In [17]: i=itertools.combinations_with_replacement((1,2,3), 4)

In [18]: next(i)
Out[18]: (1, 1, 1, 1)

In [19]: next(i)
Out[19]: (1, 1, 1, 2)

In [20]: next(i)
Out[20]: (1, 1, 1, 3)

In [21]: next(i)
Out[21]: (1, 1, 2, 2)

In [22]: 
Run Code Online (Sandbox Code Playgroud)

如果您想要所有组合的集合,包括仅按顺序不同的项目,请尝试以下方法:

# Modified from itertools.combinations_with_replace example
# from the python doc.
import itertools
import pprint
def odometer(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in itertools.product(range(n), repeat=r):
        yield tuple(pool[i] for i in indices)

pprint.pprint (list(odometer([1,2,3], 4)))
Run Code Online (Sandbox Code Playgroud)