[英]How can I make Python print all lists of given length with elements in a fixed finite set?
For example, I would like to be able to get all lists of length 5 with elements in the set {0,1,2,3}. 例如,我希望能够获得所有长度为5的列表,其中包含集合{0,1,2,3}中的元素。
I'm sure there is an easy answer but I am stuck and I don't see how to do it! 我敢肯定有一个简单的答案,但是我被困住了,我不知道该怎么做!
You're probably looking for itertools ' combinations_with_replacement
: 你可能寻找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)]
(shown for n=2
for brevity) (为简洁起见, n=2
)
If you don't count (1,2)
and (2,1)
as distinct, use roippi's answer. 如果您不将(1,2)
和(2,1)
区别开来,请使用roippi的答案。 If you do, itertools.product
(as in, "Cartesian product") works here: 如果您这样做,则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)]
Do this: 做这个:
import itertools
list(itertools.product([0,1,2,3], repeat=5))
Combinations_with_replacement will catch all cases. Combinations_with_replacement将捕获所有情况。 It treats (a,b) as the same of (a,b). 它将(a,b)与(a,b)相同。 In practice, it will only output ordered results (ex. (1,3), but not (3,1)) 实际上,它只会输出有序结果(例如(1,3),而不是(3,1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.