Reputation: 1159
For example:
s = ["ab", "cd"]
# expected output ac, ad, bc, bd
# This is easy
print([i+j for i in s[0] for j in s[1]])
# ['ac', 'ad', 'bc', 'bd']
But when the length of list is larger than two.How to achieve that with list comprehension?
s = ["ab", "cd", "ef"]
should give ace, acf, ade, adf, bce, bcf, bde, bdf
.(How to use for loop to achieve that if we don't use recursion?)
Upvotes: 1
Views: 227
Reputation: 92440
What you are looking for is the product of these sequences. itertools.product
does just this. The only complication is turning the sequences back into strings, which you can do with join()
:
from itertools import product
s = ["ab", "cd", "ef"]
list(map(''.join, product(*s)))
# ['ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf']
You can also use a list comprehension if you prefer:
[''.join(t) for t in product(*s)]
You can of course do this yourself with a simple recursive function. That might look something like:
s = ["ab", "cd", "ef"]
def product(l):
if len(l) == 0:
yield ''
return
start, *rest = l
for c in start:
for sublist in product(rest):
yield c + sublist
list(product(s))
# ['ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf']
Upvotes: 4