0

I have 3 lists as below:

list1 = [a,b,c]
list2=[1,3,5]
list3 =[d,e,f]

I want output like below: [a1d,a1e,a1f,a3d,a3e,a3f,a5d,a5e,a5f,b1d,b1e,b1f,b3e,b3d,b3f and so on]

I tried using itertools but not getting what I want. Please tell what can be used. As mentioned in combinations between two lists?

3 Answers3

1

list 1 and 2 do not contain strings, so they need to be enclosed with quotation marks.

I've also added a map to string to convert the ints to string.

The final code should be:

import  itertools
list1 = ["a","b","c"]
list2=[1,3,5]
list3 =["d","e","f"]

print([''.join(map(str,t)) for t in itertools.product(list1, list2, list3)])

This gives the following output:

['a1d', 'a1e', 'a1f', 'a3d', 'a3e', 'a3f', 'a5d', 'a5e', 'a5f', 'b1d', 'b1e', 'b1f', 'b3d', 'b3e', 'b3f', 'b5d', 'b5e', 'b5f', 'c1d', 'c1e', 'c1f', 'c3d', 'c3e', 'c3f', 'c5d', 'c5e', 'c5f']
AleksanderGD
  • 414
  • 5
  • 10
mahdilamb
  • 535
  • 3
  • 11
1

An easier way to understand it if you're starting programming is triple loop on both of your lists.

list1 = ['a','b','c']
list2=[1,3,5]
list3 =['d','e','f']

res = []

for i1 in list1:
    for i2 in list2:
        for i3 in list3:
            res.append(str(i1) + str(i2) + str(i3)) # "+" operator acts as concatenation with Strings
print(res)

Output : ['a1d', 'a1e', 'a1f', 'a3d', 'a3e', 'a3f', 'a5d', 'a5e', 'a5f', 'b1d', 'b1e', 'b1f', 'b3d', 'b3e', 'b3f', 'b5d', 'b5e', 'b5f', 'c1d', 'c1e', 'c1f', 'c3d', 'c3e', 'c3f', 'c5d', 'c5e', 'c5f']

Also don't forget to put quotes (simple or double) between your a, b, c, ... since there are characters (String types) and not variables

Adept
  • 522
  • 3
  • 16
0

Works with any number of lists:

pools = [["a","b","c"], [1,3,5], ["d","e","f"]]
result = [[]]
for pool in pools:
    result = [x+[y] for x in result for y in pool]
result = ["".join([str(x) for x in lst]) for lst in result]

print(result)

out:

['a1d', 'a1e', 'a1f', 'a3d', 'a3e', 'a3f', 'a5d', 'a5e', 'a5f', 'b1d', 'b1e', 'b1f', 'b3d', 'b3e', 'b3f', 'b5d', 'b5e', 'b5f', 'c1d', 'c1e', 'c1f', 'c3d', 'c3e', 'c3f', 'c5d', 'c5e', 'c5f']
Andreas
  • 8,694
  • 3
  • 14
  • 38