简体   繁体   中英

How to combine strings in list with a list comprehension?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM