-1

例如,我希望能够获取所有长度为 5 的列表,其中包含集合 {0,1,2,3} 中的元素。

我敢肯定有一个简单的答案,但我被卡住了,我不知道该怎么做!

4

3 回答 3

3

您可能正在寻找itertools ' combinations_with_replacement

list(itertools.combinations_with_replacement(range(4),2))
Out[18]: 
[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
 (1, 1),
 (1, 2),
 (1, 3),
 (2, 2),
 (2, 3),
 (3, 3)]

n=2为简洁起见)

于 2013-10-24T20:01:59.883 回答
2

如果您不计算(1,2)并且(2,1)不同,请使用 roippi 的答案。如果你这样做,itertools.product(如“笛卡尔积”)在这里工作:

>>> import itertools
>>> itertools.product(range(5), repeat=2)
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)]
于 2013-10-24T20:13:25.063 回答
0

做这个:

import itertools    
list(itertools.product([0,1,2,3], repeat=5))

Combinations_with_replacement 将捕获所有情况。它将 (a,b) 视为与 (a,b) 相同。在实践中,它只会输出有序的结果(例如(1,3),而不是(3,1))

于 2013-10-24T20:21:21.823 回答