[英]Add two lists which return a list the addition of the adjacent element
我想写一个 function add_list
,它添加两个列表相邻元素。 例如l1 = [1, 2, 3]
, l2= [1,2,3]
应该给出[2,4,6]
。 我迷路了,不知道如何使用循环来处理它。 有人可以帮忙吗?
您可以使用zip
迭代这两个列表,然后对它们使用list comprehension
[x+y for x,y in zip(l1, l2)]
样品运行:
>>l1 = [1, 2, 3]
>>l2= [1,2,3]
>>[x+y for x,y in zip(l1, l2)]
[2, 4, 6]
其他可能的解决方案是遍历索引(也可用于列表理解)
result = []
for i in range(len(l1)):
result.append(l1[i] + l2[i])
Output:
>>result
[2, 4, 6]
以下代码将在两个给定列表中添加数字,前提是两者具有相同数量的元素
def add_list(a, b):
result = [] # empty list
# loop through all the elements of the list
for i in range(len(a)):
# insert addition into results
result.append(a[i] + b[i])
return result
l1 = [1, 2, 3]
l2 = [1, 2, 3]
print(add_list(l1, l2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.