2013-07-31 49 views
2

我想帶一個列表,例如List = [1,2,2],併產生了排列。我可以這樣做:操縱和itertools.permutations的輸出在python

NewList = [list(itertools.permutations(List))] 

,輸出是:

[[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]] 

問題:itertools.permutations返回其唯一條目列出的所有排列的名單長度爲1的列表。那就是:

NewList[0] == [(1,2,2),(1,2,2),(2,1,2),(2,2,1),(2,1,2),(2,2,1)] 

NewList[1]不存在。

我所要的輸出是一個列表,其中每個條目的排列之一。那是

NewList[0] == (1,2,2) 
NewList[1] == (1,2,2) 
NewList[2] == (2,1,2) 
... 
NewList[5] == (2,2,1) 

問題:有沒有一種命令能夠以這種方式產生List的排列?如果沒有,有沒有辦法訪問[list(itertools.permutations(List))]的「個別元素」,所以我可以用它們做些事情?

+0

只是刪除了'[]'你已經發布的輸出也是不正確的,它應該是:'[[(1,2,2),(1 (2,2,1),(2,2,1),(2,1,2),(2,2,1)]]] –

回答

3
>>> from itertools import permutations 
>>> list(permutations([1,2,2])) 
[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)] 

你不需要再把它放在列表中。即不要做[list(permutations(...))](通過做[]你做了一個嵌套列表,因此無法訪問使用testList[index]的元素,儘管你可以做testList[0][index],但是最好把它保存爲元組列表。)

現在
>>> newList = list(permutations([1, 2, 2])) 
>>> newList[0] 
(1, 2, 2) 
>>> newList[3] 
(2, 2, 1) 

您可以通過使用其索引訪問元素。

0

爲什麼你不能做到這一點:

NewList = [list(itertools.permutations(List))][0] 

甚至只是這樣的:

NewList = list(itertools.permutations(List)) 

這樣做[ list(itertools.permutations(List)) ],你把排列的列表(你想要的)裏面的另一個列表。因此,解決將是把外[]