按元素添加2个列表? [英] Element-wise addition of 2 lists?

查看:46
本文介绍了按元素添加2个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

我希望拥有:

[1, 2, 3]
 +  +  +
[4, 5, 6]
|| || ||
[5, 7, 9]

仅是两个列表的元素加法.

Simply an element-wise addition of two lists.

我当然可以遍历两个列表,但是我不想这么做.

I can surely iterate the two lists, but I don't want do that.

最Python化的方式是什么?

推荐答案

使用 c1> operator.add :

>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]

zip 具有列表理解:

or zip with a list comprehension:

>>> [sum(x) for x in zip(list1, list2)]
[5, 7, 9]

时间比较:

>>> 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

这篇关于按元素添加2个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆