Jasper
Jasper

Reputation: 628

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]

Upvotes: 1

Views: 332

Answers (3)

MattH
MattH

Reputation: 38247

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

Upvotes: 2

Not_a_Golfer
Not_a_Golfer

Reputation: 49187

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

Upvotes: 4

John La Rooy
John La Rooy

Reputation: 304157

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

Upvotes: 1

Related Questions