列出所有组合

List all combinations

我有一个列表 [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...
]

也许 itertools 有答案?

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]: 

如果您想要所有组合的集合,包括仅顺序不同的项目,试试这个:

# 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)))