Iterate over string with commas

Question:

I have two strings:

x = 'a1,a2,a3'
y = 'b1,b2,b3'

I want to concatenate these two string as:

z = ['a1b1','a1b2','a1b3','a2b1','a2b2','a2b3','a3b1','a3b2','a3b3']

I used the code snippet:

for i in x:
     for j in y:
         z.append(i+j)

But the result was not as required. How can I obtain the required result?

Asked By: Lalit Jain

||

Answers:

You can use starmap on the product with the add operator for that

from operator import add
from itertools import starmap, product
x = 'a1,a2,a3'
y = 'b1,b2,b3'
z=list(starmap(add, product(x.split(','),y.split(','))))
Answered By: Uri Goren

You need to str.splitsplit the strings on ",", then you can use itertools.product to get the cartesian product of the two lists:

from itertools import product

x = "a1,a2,a3"
y = "b1,b2,b3"

print([fst + snd for fst, snd in product(x.split(","), y.split(","))])
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']

You could also do this nested loops in a list comprehension to achieve the same result:

print([fst + snd for fst in x.split(",") for snd in y.split(",")])
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']

Or use a solution similar to your original approach:

z = []
for fst in x.split(","):
    for snd in y.split(","):
        z.append(fst + snd)

print(z)
# ['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']
Answered By: RoadRunner

This is what you are looking for.

x = 'a1,a2,a3'.split(',')
y = 'b1,b2,b3'.split(',')


[a+b for a in x for b in y]

Answered By: jawad-khan

A very straitghfoward method would be

x = ['a1', 'a2', 'a3']
y = ['b1', 'b2', 'b3']

[(i+j) for i in x for j in y]

#['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']
Answered By: Luciana da Costa
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.