2017-06-29 118 views
2

我怎樣才能得到列表中的所有可能的值列表也重複?獲取與重複值的列表的所有組合

我試過itertools.combination_with_replacementitertools.permutation,但第一個排除倒排順序(如[3, 2, 1]),第二個排除多個值(如[3, 3, 1])。

我需要的是這樣的:

例子:

list = [1, 2, 3] 

results = 
[1, 1, 1] 
[1, 1, 2] 
[1, 1, 3] 
... 
[3, 1, 1] 
[3, 1, 2] 
[3, 1, 3] 
... 

我可以在Python做些什麼來實現這一目標? 在此先感謝。

回答

4

您正在尋找itertools.product,重複設置爲3:

>>> from itertools import product 
>>> lst = [1, 2, 3] 
>>> list(product(lst, repeat=3)) 
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)] 
+1

非常感謝你! –