Vincent Heng
Vincent Heng

Reputation: 43

loop and merge to create new list

what is the most efficient way of doing the following?

A = ["A","B","C"]
B = [range(19,21)]

Outcome of the list:

C = ["A19", "B19", "C19", "A20", "B20", "C20"] 

thanks very much!

Upvotes: 2

Views: 61

Answers (4)

Camile
Camile

Reputation: 107

For range in the list:

B = [*range(19, 21)]:

C = [a + str(b) for b in B for a in A]

Upvotes: 0

Mykola Zotko
Mykola Zotko

Reputation: 17824

You can use the following listcomp:

from itertools import product

A = ["A","B","C"]
B = range(19,21)

[i + j for i, j in product(A, map(str, B))]
# ['A19', 'A20', 'B19', 'B20', 'C19', 'C20']

or

from itertools import product
from operator import concat

[concat(*i) for i in product(A, map(str, B))]
# ['A19', 'A20', 'B19', 'B20', 'C19', 'C20']

If you want to build a list from a range use the function list():

list(range(19, 21))
# [19, 20]

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

Use a list comprehension:

A = ["A","B","C"]
B = range(19,21)
print([x+str(y) for y in B for x in A])

Or if version is above Python 3.6:

print([f"{x}{y}" for y in B for x in A])

Output:

['A19', 'B19', 'C19', 'A20', 'B20', 'C20']

Edit:

Use this:

A = ["X","Y","Z"]
B = range(19,21)
C = [x+str(y) for y in B for x in A]
print(C)
curveexpression = ""
for zoo in "Animal":
    for month in C:
        arrival += "[%s,%s];" % (zoo, month)
print(arrival)

Upvotes: 3

hiro protagonist
hiro protagonist

Reputation: 46859

itertools.product could also be used:

from itertools import product

A = ["A","B","C"]
C = [a + str(n) for n, a in product(range(19, 21), A)]

note that there are different ways to format the string (a) and the number n to a single string:

a + str(n)
"{}{}".format(a, n)
f"{a}{n}"  # for python >= 3.6

Upvotes: 5

Related Questions