循环并合并以创建新列表

时间:2019-03-21 08:37:07

标签: python loops join merge

执行以下操作的最有效方法是什么?

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

列表结果:

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

非常感谢!

4 个答案:

答案 0 :(得分:5)

itertools.product也可以使用:

from itertools import product

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

请注意,有多种方法可以将字符串(a)和数字n格式化为单个字符串:

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

答案 1 :(得分:3)

使用列表理解:

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

或者版本高于Python 3.6:

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

输出:

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

编辑:

使用此:

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)

答案 2 :(得分:0)

您可以使用以下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']

from itertools import product
from operator import concat

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

如果要从某个范围构建列表,请使用函数list()

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

答案 3 :(得分:0)

对于列表中的范围:

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

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