在列表中进行所有可能的列表组合

时间:2012-05-21 09:46:39

标签: python list combinations

我已经找到了这个问题的几个答案,但这不是我打算做的。

当我有一个清单时:

[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]

3 个答案:

答案 0 :(得分: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]]

答案 1 :(得分: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 :(得分: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])]