-1

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Lalit Jain
  • 363
  • 2
  • 14
  • The actual **problem** here was with splitting the input strings - while `itertools.product` is the right tool for producing the cartesian product, the approach was fine except for the part where iterating *over the individual strings* doesn't do what's needed. This was therefore closed with completely the wrong duplicate. The question is about how to treat the string `'a1,a2,a3'` as though it contained three strings `'a1'`, `'a2'`, `'a3'`; and that is a duplicate of the question about **how to split strings**. I have fixed this now. – Karl Knechtel Feb 18 '23 at 19:07

4 Answers4

4

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]

jawad-khan
  • 313
  • 1
  • 10
3

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(','))))
Uri Goren
  • 13,386
  • 6
  • 58
  • 110
3

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']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
1

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']