2017-06-03 119 views
0
from itertools import permutations 
l = [0, 1, 2, 3, 4] 
x = permutations (l, 3) 

每個排列我得到以下幾點:列表的迭代

(0, 1, 2) , (0, 1, 3), ...., (0, 2, 1), (0, 2, 3), (0,2,4),...., (4, 3, 0), (4, 3, 1), 
(4, 3, 2) 

這是什麼預期。 但我需要的是:

(0, 0, 0), (0, 0, 1), ...., (0, 0, 4), (0, 1, 0), (0, 1, 1)........ 

如何實現這一目標?

+0

你沒有解釋結果應該包含什麼。但請檢查itertools中的其他函數以查看是否符合您的需求。 –

回答

2

你需要的是一個置換與更換,或一個產品,而是itertoolpermutations產生排列無需更換。您可以自己計算一下產品:

[(x,y,z) for x in l for y in l for z in l] 
#[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0), ... 

或者從itertools使用同名函數:

list(itertools.product(l,repeat=3)) 
# [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0),... 

後一種方法更有效。

1

您需要使用product,不使用permutations,從itertools模塊這樣的例子:

from itertools import product 

l = [0, 1, 2, 3, 4] 
# Or: 
# b = list(product(l, repeat=3)) 
b = list(product(l,l,l)) 
print(b) 

輸出:

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), ..., (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 4, 4)] 
0

您需要的產品,而不是置換

from itertools import product 
l = [0, 1, 2, 3, 4] 
b = list(product(l, repeat=3))