简体   繁体   English

循环并合并以创建新列表

[英]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! 非常感谢!

itertools.product could also be used: 也可以使用itertools.product

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 )和数字n格式化为单个字符串:

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

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: 或者如果版本高于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)

You can use the following listcomp: 您可以使用以下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()

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

For range in the list: 对于列表中的范围:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM