python:逐点列表总和

标签 python list

Input: two lists (list1, list2) of equal length
Output: one list (result) of the same length, such that:
    result[i] = list1[i] + list2[i]

有什么简洁的方法可以做到这一点吗?或者这是最好的:

# Python 3
assert len(list1) == len(list2)
result = [list1[i] + list2[i] for i in range(len(list1))]

最佳答案

您可以使用内置的 zip函数,或者您也可以使用 do it 将两个列表映射到 add 运算符上。像这样:

from operator import add
map(add, list1,list2)

关于python:逐点列表总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5788470/

相关文章:

python - Sphinx-build 不能被识别为内部或外部命令

python - 使用 Spyder/Python 打开 .npy 文件

python - Django websockets 实现

python - 如何执行两个列表的逐元素乘法?

jquery - 向用户展示大量数据的有效方法有哪些?

python - 从两个列表中创建一个新列表,其中一个列表缺少数据 - 只应接受有效的对应值

Python 日志记录和子进程输出和错误流

python - 在seaborn/matplotlib中保持x/y轴相同的长度

python - 将字符串转换为元组而不拆分字符

python - 从重复出现的单词右侧的 n 个元素形成新列表