简体   繁体   中英

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?

Thanks, and is it also possible to create 1 list instead of 3 like: [7,8,9,4,5,6,1,2,3]

itertools.permutations is what you're looking for I think.

>>> 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 :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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