Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python all combinations of a list of lists

So I have a list of lists of strings

[['a','b'],['c','d'],['e','f']]

and I want to get all possible combinations, such that the result is

[['a','b'],['c','d'],['e','f'],
 ['a','b','c','d'],['a','b','e','f'],['c','d','e','f'],
 ['a','b','c','d','e','f']]

So far I have come up with this code snippet

input = [['a','b'],['c','d'],['e','f']]
combs = []
for i in xrange(1, len(input)+1):
    els = [x for x in itertools.combinations(input, i)]
    combs.extend(els)
print combs

largely following an answer in this post.

But that results in

[(['a','b'],),(['c','d'],),(['e','f'],),
 (['a','b'],['c','d']),(['a','b'],['e','f']),(['c','d'],['e','f']),
 (['a','b'],['c', 'd'],['e', 'f'])]

and I am currently stumped, trying to find an elegant, pythonic way to unpack those tuples.

like image 845
Matt M. Avatar asked Oct 14 '15 15:10

Matt M.


1 Answers

You can use itertools.chain.from_iterable to flatten the tuple of lists into a list. Example -

import itertools
input = [['a','b'],['c','d'],['e','f']]
combs = []
for i in xrange(1, len(input)+1):
    els = [list(itertools.chain.from_iterable(x)) for x in itertools.combinations(input, i)]
    combs.extend(els)

Demo -

>>> import itertools
>>> input = [['a','b'],['c','d'],['e','f']]
>>> combs = []
>>> for i in range(1, len(input)+1):
...     els = [list(itertools.chain.from_iterable(x)) for x in itertools.combinations(input, i)]
...     combs.extend(els)
...
>>> import pprint
>>> pprint.pprint(combs)
[['a', 'b'],
 ['c', 'd'],
 ['e', 'f'],
 ['a', 'b', 'c', 'd'],
 ['a', 'b', 'e', 'f'],
 ['c', 'd', 'e', 'f'],
 ['a', 'b', 'c', 'd', 'e', 'f']]
like image 87
Anand S Kumar Avatar answered Oct 21 '22 23:10

Anand S Kumar