首页 > 后端开发 > Python教程 > 在 Python 中执行列表按元素添加的最有效方法是什么?

在 Python 中执行列表按元素添加的最有效方法是什么?

Mary-Kate Olsen
发布: 2024-11-26 16:00:12
原创
768 人浏览过

What's the Most Efficient Way to Perform Element-Wise Addition of Lists in Python?

列表的按元素添加:Pythonic 方法

按元素添加两个列表可以在 Python 中使用多个内置函数轻松执行在函数中。以下是如何在不进行繁琐迭代的情况下实现此目的的方法:

map() 与 operator.add 结合使用:

from operator import add
result = list(map(add, list1, list2))
登录后复制

map() 函数将 add 函数应用于每个list1 和 list2 中对应的元素,返回结果列表。

或者,使用带有列表理解的 zip():

result = [sum(x) for x in zip(list1, list2)]
登录后复制

zip() 函数将 list1 和 list2 中的元素配对成元组序列。然后列表推导式计算每个元组的总和,产生逐元素加法。

性能比较:

为了比较这些方法的效率,我们进行了计时在大型列表(100,000 个元素)上进行测试:

>>> from itertools import izip
>>> list2 = [4, 5, 6] * 10 ** 5
>>> list1 = [1, 2, 3] * 10 ** 5

>>> %timeit from operator import add; map(add, list1, list2)
10 loops, best of 3: 44.6 ms per loop

>>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]
10 loops, best of 3: 71 ms per loop

>>> %timeit [a + b for a, b in zip(list1, list2)]
10 loops, best of 3: 112 ms per loop

>>> %timeit from itertools import izip; [sum(x) for x in izip(list1, list2)]
1 loops, best of 3: 139 ms per loop

>>> %timeit [sum(x) for x in zip(list1, list2)]
1 loops, best of 3: 177 ms per loop
登录后复制

如这些结果所示, map() 使用operator.add 的方法对于大型列表来说是最快的。

以上是在 Python 中执行列表按元素添加的最有效方法是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板