Get joined string from list of lists of strings in Python

from itertools import product
result = [separator.join(map(str,x)) for x in product(*lists)]

itertools.product returns an iterator that produces the cartesian product of the provided iterables. We need to map str over the resultant tuples, since some of the values are ints. Finally, we can join the stringified tuples and throw the whole thing inside a list comprehension (or generator expression if dealing with a large dataset, and you just need it for iteration).


>>> from itertools import product
>>> result = list(product(*lists))
>>> result = [separator.join(map(str, r)) for r in result]
>>> result
['a-1-i', 'a-1-ii', 'a-2-i', 'a-2-ii', 'b-1-i', 'b-1-ii', 'b-2-i', 'b-2-ii']

As @jpm pointed out, you don't really need to cast list to the product generator. I had these to see the results in my console, but they are not really needed here.

Tags:

Python