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

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

问题描述

我现在有:

list1 = [1, 2, 3]列表 2 = [4, 5, 6]

我希望:

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

简单地将两个列表按元素相加.

我当然可以迭代这两个列表,但我不想这样做.

最 Pythonic 的方法是什么?

解决方案

使用 mapoperator.添加:

<预><代码>>>>从操作符导入添加>>>列表(地图(添加,列表1,列表2))[5, 7, 9]

或带有列表的zip领悟:

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

时间比较:

<预><代码>>>>list2 = [4, 5, 6]*10**5>>>列表 1 = [1, 2, 3]*10**5>>>%timeit from operator import add;map(add, list1, list2)10 个循环,最好的 3 个:每个循环 44.6 毫秒>>>%timeit from itertools import izip;[a + b for a, b in izip(list1, list2)]10 个循环,最好的 3 个:每个循环 71 毫秒>>>%timeit [a + b for a, b in zip(list1, list2)]10 个循环,最好的 3 个:每个循环 112 毫秒>>>%timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]1 个循环,最好的 3 个:每个循环 139 毫秒>>>%timeit [sum(x) for x in zip(list1, list2)]1 个循环,最好的 3 个:每个循环 177 毫秒

I have now:

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

I wish to have:

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

What is the most Pythonic way of doing so?

解决方案

Use map with operator.add:

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

or zip with a list comprehension:

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

Timing comparisons:

>>> 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天全站免登陆