简体   繁体   English

将两个列表中的元素连接到 python 中的第三个列表中

[英]Concatenate elements from two lists into a third one in python

a = ['1', '2', '3']
b = ['a', 'b', 'c']
c = []

What can I do to get the third list to be the concatenation of the corresponding elements from lists a and b, as in:我该怎么做才能使第三个列表成为列表 a 和 b 中相应元素的串联,如:

c = ['1a', '2b', '3c']

Here is a simple while loop to do the trick:这是一个简单的while循环来解决这个问题:

a = ['1', '2', '3']
b = ['a', 'b', 'c']
c = []

counter = 0
while counter < len(a):
    c.append(a[counter] + b[counter])
    counter += 1

print(c)

Obviously, there are more elegant methods to do this, such as using the zip method:显然,还有更优雅的方法可以做到这一点,例如使用zip方法:

a = ['1', '2', '3']
b = ['a', 'b', 'c']
c = [x + y for x,y in zip(a, b)]

print(c)

Both methods have the same output:两种方法都有相同的 output:

['1a', '2b', '3c']

You can use a enumerate function to elegantly solve your problem.您可以使用枚举 function 优雅地解决您的问题。

a = ['1', '2', '3']
b = ['a', 'b', 'c']
c = []
for idx, elem in enumerate(a):
  c.append(a[idx] + b[idx])
print(c)

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

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