Combining two lists ( so [['a', 'b'], ['c', 'd']] = ['ac', 'ad', 'bc', 'bd] ) the pythonic way
Question:
Given a list of lists such as:
[['a', 'b'], ['c', 'd'], ['e']]
Result should be:
['ace', 'ade', 'bce', 'bde']
The nested lists will be different lengths. Order must be maintained — i.e. first letter must come from first list, second letter from second list, etc.
Here is my current, recursive solution:
def combine_letters(l)
if len(l) == 0:
return l[0]
temp = [x + y for x in l[0] for y in l[1]]
new = [temp] + l[2:]
return combine_letters(new)
However, I feel like there should be a quick, maybe even one line, way to do this, possible using the reduce function. Any thoughts?
Thank you!
Edit: this is not exactly analogous to the linked question. First, it is for a arbitrarily large number of sublists. Second, it returns strings rather than tuples.
Answers:
>>> L = [['a', 'b'], ['c', 'd'], ['e']]
>>> import itertools
>>> list(itertools.product(*L))
[('a', 'c', 'e'), ('a', 'd', 'e'), ('b', 'c', 'e'), ('b', 'd', 'e')]
>>> list(''.join(tup) for tup in list(itertools.product(*L)))
['ace', 'ade', 'bce', 'bde']
Given a list of lists such as:
[['a', 'b'], ['c', 'd'], ['e']]
Result should be:
['ace', 'ade', 'bce', 'bde']
The nested lists will be different lengths. Order must be maintained — i.e. first letter must come from first list, second letter from second list, etc.
Here is my current, recursive solution:
def combine_letters(l)
if len(l) == 0:
return l[0]
temp = [x + y for x in l[0] for y in l[1]]
new = [temp] + l[2:]
return combine_letters(new)
However, I feel like there should be a quick, maybe even one line, way to do this, possible using the reduce function. Any thoughts?
Thank you!
Edit: this is not exactly analogous to the linked question. First, it is for a arbitrarily large number of sublists. Second, it returns strings rather than tuples.
>>> L = [['a', 'b'], ['c', 'd'], ['e']]
>>> import itertools
>>> list(itertools.product(*L))
[('a', 'c', 'e'), ('a', 'd', 'e'), ('b', 'c', 'e'), ('b', 'd', 'e')]
>>> list(''.join(tup) for tup in list(itertools.product(*L)))
['ace', 'ade', 'bce', 'bde']