2012-05-21 183 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])]