[英]How to print elements of list in python given a a fixed sample size?
[英]How can I make Python print all lists of given length with elements in a fixed finite set?
例如,我希望能够获得所有长度为5的列表,其中包含集合{0,1,2,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
)
如果您不将(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)]
做这个:
import itertools
list(itertools.product([0,1,2,3], repeat=5))
Combinations_with_replacement将捕获所有情况。 它将(a,b)与(a,b)相同。 实际上,它只会输出有序结果(例如(1,3),而不是(3,1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.