[英]Adding each item from one list to each item from another list to third list
Image the following lists:想象以下列表:
A = [1,2,3,4]
B = ['A','B','C','D']
C = [10,11,12,13]
D = [100,200,300,400]
I should get the following results: Z = ['1A10100', '2B11200', '3C12300', '4D13400']
我应该得到以下结果: Z = ['1A10100', '2B11200', '3C12300', '4D13400']
I can do this using a lot of empty arrays, do it first using a for loop for A and B than use this new list and append C for each i, etc.我可以使用很多空数组来做到这一点,首先对 A 和 B 使用 for 循环,而不是使用这个新列表并为每个 i 附加 C,等等。
The question is, can this be done in a smarter way.问题是,这能否以更智能的方式完成。 In my real case the lists are 6?在我的真实情况下,列表是 6?
You can use a simple list comprehension:您可以使用简单的列表推导:
Z = [''.join(str(x) for x in l) for l in zip(A,B,C,D)]
output: ['1A10100', '2B11200', '3C12300', '4D13400']
输出: ['1A10100', '2B11200', '3C12300', '4D13400']
If you already have a container for your lists:如果您的列表已经有一个容器:
lists = [A,B,C,D]
[''.join(str(x) for x in l) for l in zip(*lists)]
Using a list comprehension we can try:使用列表推导,我们可以尝试:
A = [1,2,3,4]
B = ['A','B','C','D']
C = [10,11,12,13]
D = [100,200,300,400]
nums = list(range(0, len(A)))
Z = [str(A[i]) + B[i] + str(C[i]) + str(D[i]) for i in nums]
print(Z) # ['1A10100', '2B11200', '3C12300', '4D13400']
If the length of each lists are fixed and same length you can simply loop by indices, concatenate them, and then push altogether one-by-one into the result array.如果每个列表的长度是固定的且长度相同,您可以简单地按索引循环,将它们连接起来,然后将它们一一推送到结果数组中。
A = [1,2,3,4]
B = ['A','B','C','D']
C = [10,11,12,13]
D = [100,200,300,400]
# Prepare the empty array
result = []
# Concat and insert one-by-one
for i in range(len(A)):
result.append('{}{}{}{}'.format(A[i], B[i], C[i], D[i]))
print(result)
Output:输出:
['1A10100', '2B11200', '3C12300', '4D13400']
There are also another way to concatenate and insert to the result array besides the code above:除了上面的代码之外,还有另一种连接和插入结果数组的方法:
for i in range(len(A)):
tmp = str(A[i]) + B[i] + str(C[i]) + str(D[i])
result.append(tmp)
for i in range(len(A)):
result.append(f'{A[i]}{B[i]}{C[i]}{D[i]}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.