Reputation: 1
I want to create a list of every possible combination between 2 lists of elements regardless of either list's size (they may or may not be identical lengths).
I've looked through itertools examples and searched stackoverflow but haven't found an exact example of what I'm looking for.
INPUT:
l1 = ['a', 'b', 'c']
l2 = [1, 2]
OUTPUT:
['a1-b1-c1', 'a1-b1-c2', 'a1-b2-c1', 'a1-b2-c2', 'a2-b1-c1', 'a2-b1-c2', 'a2-b2-c1', 'a2-b2-c2']
but again, l1
can be any size and l2
can be any size. Don't care at all about formatting, just want the complete output.
Thanks!
Upvotes: 0
Views: 209
Reputation: 402483
You can use itertools.product
to generate all possible 3-combinations of l2
, and then join each combination with l1
.
from itertools import product
combs = product(map(str, l2), repeat=3)
['-'.join([x + y for x, y in zip(l1, c)]) for c in combs]
# ['a1-b1-c1', 'a1-b1-c2', 'a1-b2-c1', 'a1-b2-c2', 'a2-b1-c1', 'a2-b1-c2', 'a2-b2-c1', 'a2-b2-c2']
Upvotes: 2
Reputation: 304147
This solution creates a template from l1
: eg. 'a{}-b{}-c{}'
from itertools import product
l1 = ['a', 'b', 'c']
l2 = [1, 2]
template = "{}-".join(l1) + "{}"
[template.format(*c) for c in product(l2, repeat=len(l1))]
['a1-b1-c1', 'a1-b1-c2', 'a1-b2-c1', 'a1-b2-c2', 'a2-b1-c1', 'a2-b1-c2', 'a2-b2-c1', 'a2-b2-c2']
Upvotes: 1
Reputation: 106543
You can use itertools.product
:
from itertools import product
['-'.join(map(''.join, zip(l1, c))) for c in product(map(str, l2), repeat=len(l1))]
This returns:
['a1-b1-c1', 'a1-b1-c2', 'a1-b2-c1', 'a1-b2-c2', 'a2-b1-c1', 'a2-b1-c2', 'a2-b2-c1', 'a2-b2-c2']
Upvotes: 0
Reputation: 7740
You can use itertools.product
and list comprehensions to get the result you are after:
from itertools import product
result = ["-".join(y+str(z) for y, z in zip(l1, x)) for x in product(*[l2] * 3)]
I would like to note that approach does not produce any extra intermediate combinations.
Output:
['a1-b1-c1', 'a1-b1-c2', 'a1-b2-c1', 'a1-b2-c2', 'a2-b1-c1', 'a2-b1-c2', 'a2-b2-c1', 'a2-b2-c2']
Upvotes: 0