简体   繁体   English

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

[英]Making all possible combination of lists in lists

I have found several answers to this problem, however it is not what i intended to do. 我已经找到了解决这个问题的几种方法,但这不是我打算做的。

When I have a list: 当我有清单时:

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

And I would like to have all possible combinations: 我想拥有所有可能的组合:

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

But is there an easy solution for this in python? 但是在python中有一个简单的解决方案吗?

Thanks, and is it also possible to create 1 list instead of 3 like: [7,8,9,4,5,6,1,2,3] 谢谢,也可以创建1个列表而不是3个列表,例如:[7,8,9,4,5,6,1,2,3]

itertools.permutations is what you're looking for I think. 我认为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])]

And merged together: 并合并在一起:

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

Combined lists using reduce : 使用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]

In Python2.7 you don't need to specify the length of the permutations 在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])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM