I have a list of lists and a separator string like this:
lists = [
separator = '-'
As result I want to have a list of strings combined with separator string from the strings in the sub lists:
result = [
Order in result is irrelevant.
How can I do this?
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
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.
You can do this with builtins:
>>> map(separator.join, reduce(lambda c,n: [a+[str(b)] for b in n for a in c], lists, [])) ['a-1-i', 'b-1-i', 'a-2-i', 'b-2-i', 'a-1-ii', 'b-1-ii', 'a-2-ii', 'b-2-ii']
["%s%c%s%c%s" % (a, separator, b, separator, c) for a in lists for b in lists for c in lists]