2017-06-03 203 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))