我已经找到了这个问题的几个答案,但这不是我想要做的。
当我有一个列表时:
[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]]
