2012-05-21 181 views
1

我發現了這個問題的幾個答案,但它不是我想要做的。在列表中列出所有可能的列表組合

當我有一個列表:

[1,2,3],[4,5,6],[7,8,9] 

我想有所有可能的組合:

[1,2,3],[7,8,9],[4,5,6] 
[1,2,3],[4,5,6],[7,8,9] 
[7,8,9],[4,5,6],[1,2,3] 
.... 

但有一個簡單的解決方案,這在Python?

感謝了,是不是也可以創建1名列表,而不是像3: [7,8,9,4,5,6,1,2,3]

+0

該列表是否故意重複兩次? – jamylak

+0

對不起,我會改變它 – Jasper

+0

@xienixs:最好不要移動目標文章,你已經有問題的答案,因爲它剛剛站起來。 – MattH

回答

4

itertools.permutations是你在做什麼尋找我的想法。

>>> import itertools 
>>> l = [1,2,3],[4,5,6],[7,8,9] 
>>> list(itertools.permutations(l, len(l))) 
[([1, 2, 3], [4, 5, 6], [7, 8, 9]), 
    ([1, 2, 3], [7, 8, 9], [4, 5, 6]), 
    ([4, 5, 6], [1, 2, 3], [7, 8, 9]), 
    ([4, 5, 6], [7, 8, 9], [1, 2, 3]), 
    ([7, 8, 9], [1, 2, 3], [4, 5, 6]), 
    ([7, 8, 9], [4, 5, 6], [1, 2, 3])] 

併合並在一起:

>>> [list(itertools.chain(*x)) for x in itertools.permutations(l, len(l))] 

[[1, 2, 3, 4, 5, 6, 7, 8, 9], 
[1, 2, 3, 7, 8, 9, 4, 5, 6], 
[4, 5, 6, 1, 2, 3, 7, 8, 9], 
[4, 5, 6, 7, 8, 9, 1, 2, 3], 
[7, 8, 9, 1, 2, 3, 4, 5, 6], 
[7, 8, 9, 4, 5, 6, 1, 2, 3]] 
+0

完美!對不起,但現在我正在使用它也可以取代[1,2,3],[4,5,6],[7,8,9]創建[1,2,3,4,5,6 ,7,8,9]?只有一個列表而不是3個? – Jasper

+0

你的意思是將3的每個組合合併成一行?或排列在整個行?你也可以做。如果你想合併3個memeber變換,在itertools.permutations(l,len(l))]' –

2
>>> from itertools import permutations 
>>> a = [[1,2,3],[4,5,6],[7,8,9]] 
>>> for permu in permutations(a,3): 
... print permu 
... 
([1, 2, 3], [4, 5, 6], [7, 8, 9]) 
([1, 2, 3], [7, 8, 9], [4, 5, 6]) 
([4, 5, 6], [1, 2, 3], [7, 8, 9]) 
([4, 5, 6], [7, 8, 9], [1, 2, 3]) 
([7, 8, 9], [1, 2, 3], [4, 5, 6]) 
([7, 8, 9], [4, 5, 6], [1, 2, 3]) 

組合列表使用reduce

>>> a = [[1,2,3],[4,5,6],[7,8,9]] 
>>> for permu in permutations(a,3): 
... print reduce(lambda x,y: x+y,permu,[]) 
... 
[1, 2, 3, 4, 5, 6, 7, 8, 9] 
[1, 2, 3, 7, 8, 9, 4, 5, 6] 
[4, 5, 6, 1, 2, 3, 7, 8, 9] 
[4, 5, 6, 7, 8, 9, 1, 2, 3] 
[7, 8, 9, 1, 2, 3, 4, 5, 6] 
[7, 8, 9, 4, 5, 6, 1, 2, 3] 
+2

Dagnabbit中使用'[list(itertools.chain(* x)),受到「你是人類」驗證碼錯過了8秒的第一個答案。 – MattH

+0

嘿,我也懂了,只是想到了一個簡單的CAPTCHA;) –

+0

我的東西在'S'和'$'之間的中間......燒了幾秒鐘後決定! – MattH

1

在Python2.7你不需要指定排列的長度

>>> T=[1,2,3],[4,5,6],[7,8,9] 
>>> from itertools import permutations 
>>> list(permutations(T)) 
[([1, 2, 3], [4, 5, 6], [7, 8, 9]), ([1, 2, 3], [7, 8, 9], [4, 5, 6]), ([4, 5, 6], [1, 2, 3], [7, 8, 9]), ([4, 5, 6], [7, 8, 9], [1, 2, 3]), ([7, 8, 9], [1, 2, 3], [4, 5, 6]), ([7, 8, 9], [4, 5, 6], [1, 2, 3])]