在 Python 中从相同长度的列表中添加值

spi*_*paz 1 python arrays loops tuples python-3.x

我想添加两个(可能更多用于扩展能力)列表或元组的每个值,并返回另一个具有相应值总和的可迭代对象。

这是两个填充了任意值的列表。

l1 = [90, 7, 30, 6]
l2 = [8,  2, 40, 5]
Run Code Online (Sandbox Code Playgroud)

当然,用加号运算符添加它们只是简单地连接。

l1 + l2 = [90, 7, 30, 6, 8, 2, 40, 5]
Run Code Online (Sandbox Code Playgroud)

除了遍历它之外,是否有一种简单的方法可以将每个值添加到相应列表或元组中的匹配项中?

l1 + l2 = [98, 9, 70, 11]
Run Code Online (Sandbox Code Playgroud)

这就是我需要的,我真的认为必须有一种比制作迭代函数更简单的方法来做到这一点。

谢谢。

Aja*_*234 6

您需要使用zip

l1 = [90, 7, 30, 6]
l2 = [8,  2, 40, 5]

new = [a+b for a, b in zip(l1, l2)]
Run Code Online (Sandbox Code Playgroud)

输出:

[98, 9, 70, 11]
Run Code Online (Sandbox Code Playgroud)