Python all list list combinations

So I have a list of string lists

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

and I want to get all the possible combinations, so the result

 [['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 found this piece of code

 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 

mostly after responding to this post .

But this leads to

 [(['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'm currently a dead end trying to find an elegant, pufonic way to unpack these tuples.

+5
source share
4 answers

You can use itertools.chain.from_iterable to flatten the list of lists in 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']] 
+6
source

One of the ideas for this purpose is to display the integers from [0..2**n-1] , where n is the number of subscriptions for your entire target element in accordance with a very simple rule: Take an index element k if (2**k)&i!=0 , where I run through [0..2**n-1] . In other words, I need to read bitwise, and for each bit set, the corresponding element from l is saved. From a mathematical point of view, this is one of the cleanest ways to achieve what you want to do, since it carefully follows the definition of the parts of the set (where you have exactly 2**n parts for a set with n elements).

Didn't try, but something like this should work:

 l = [['a','b'],['c','d'],['e','f']] n = len(l) output = [] for i in range(2**n): s = [] for k in range(n): if (2**k)&i: s = s + l[k] output.append(s) 

If you do not need an empty list, simply replace the corresponding line as follows:

 for i in range(1,2**n): 
0
source

If you want all the combinations, you can consider this simple way:

 import itertools a = [['a','b'],['c','d'],['e','f']] a = a + [i + j for i in a for j in a if i != j] + [list(itertools.chain.from_iterable(a))] 
0
source

With understanding lists:

 combs=[sum(x,[]) for i in range(len(l)) for x in itertools.combinations(l,i+1)] 
0
source

Source: https://habr.com/ru/post/1233720/


All Articles