我已经找到了这个问题的几个答案,但这不是我打算做的。
当我有一个清单时:
[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]
我已经找到了这个问题的几个答案,但这不是我打算做的。
当我有一个清单时:
[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]
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]]
>>> 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]
在 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])]