![](/img/trans.png)
[英]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.