热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

两个列表的元素相加?-Element-wiseadditionof2lists?

Ihavenow:我现在:list1[1,2,3]list2[4,5,6]Iwishtohave:我希望有:[1,2,3]+++[4

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?

最符合python语言的方法是什么?

13 个解决方案

#1


243  

Use map with operator.add:

使用地图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


75  

The others gave examples how to do this in pure python. If you want to do this with arrays with 100.000 elements, you should use numpy:

其他人给出了在纯python中如何实现这一点的示例。如果你想用100.000个元素的数组来做这个,你应该使用numpy:

In [1]: import numpy as np
In [2]: vector1 = np.array([1, 2, 3])
In [3]: vector2 = np.array([4, 5, 6])

Doing the element-wise addition is now as trivial as

现在做元素加法就像做一样简单

In [4]: sum_vector = vector1 + vector2
In [5]: print sum_vector
[5 7 9]

just like in Matlab.

就像在Matlab。

Timing to compare with Ashwini's fastest version:

与Ashwini最快版本进行比较的时机:

In [16]: from operator import add
In [17]: n = 10**5
In [18]: vector2 = np.tile([4,5,6], n)
In [19]: vector1 = np.tile([1,2,3], n)
In [20]: list1 = [1,2,3]*n
In [21]: list2 = [4,5,6]*n
In [22]: timeit map(add, list1, list2)
10 loops, best of 3: 26.9 ms per loop

In [23]: timeit vector1 + vector2
1000 loops, best of 3: 1.06 ms per loop

So this is a factor 25 faster! But use what suits your situation. For a simple program, you probably don't want to install numpy, so use standard python (and I find Henry's version the most pythonic one). If you are into serious number crunching, let numpy do the heavy lifting. For the speed freaks: it seems that the numpy solution is faster starting around n = 8.

这比原来快了25倍!但是要用适合你的情况。对于一个简单的程序,您可能不想安装numpy,所以使用标准的python(我发现Henry的python版本是最python化的)。如果你是认真的数字处理,让numpy做繁重的举重。对于速度狂:似乎从n = 8开始,麻木的解速度更快。

#3


49  

[a + b for a, b in zip(list1, list2)]

#4


6  

As described by others, a fast and also space efficient solution is using numpy (np) with it's built-in vector manipulation capability:

正如其他人所描述的,使用numpy (np)和它内置的矢量操作能力是一种快速且空间高效的解决方案:

1. With Numpy

1。与Numpy

x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y

2. With built-ins

2。与整体功能

2.1 Lambda

2.1λ

list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)

Notice that map() supports multiple arguments.

注意,map()支持多个参数。

2.2 zip and list comprehension

2.2压缩和列表理解

list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]

#5


4  

Perhaps "the most pythonic way" should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.

也许“最python化的方式”应该包括处理清单1和清单2大小不同的情况。运用其中的一些方法,你会得到一个答案。numpy方法会让您知道,很可能是一个ValueError。

Example:

例子:

import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
  File "", line 1, in 
ValueError: operands could not be broadcast together with shapes (2) (3)

Which result might you want if this were in a function in your problem?

如果这是问题中的函数,你想要的结果是什么?

#6


3  

This will work for 2 or more lists; iterating through the list of lists, but using numpy addition to deal with elements of each list

这将适用于两个或多个列表;遍历列表,但使用numpy加法处理每个列表的元素

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

lists = [list1, list2]
list_sum = np.zeros(len(list1))
for i in lists:
   list_sum += i
list_sum = list_sum.tolist()    

[5.0, 7.0, 9.0]

#7


2  

Use map with lambda function:

使用map with lambda函数:

>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]

#8


2  

I haven't timed it but I suspect this would be pretty quick:

我还没有计时,但我想这可能会很快:

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

list_sum = (np.add(list1, list2)).tolist()

[5, 7, 9]

#9


2  

It's simpler to use numpy from my opinion:

从我的观点来看,使用numpy更简单:

import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)

Results:

结果:

Terminal execution

For detailed parameter information, check here: numpy.add

有关详细的参数信息,请在这里检查:numpi .add

#10


1  

If you need to handle lists of different sizes, worry not! The wonderful itertools module has you covered:

如果你需要处理不同大小的列表,不用担心!精彩的itertools模块已经介绍了:

>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
>>>

In Python 2, zip_longest is called izip_longest.

在Python 2中,zip_longest被称为izip_longest。

See also this relevant answer and comment on another question.

另一个问题的回答和评论,请参看。

#11


1  

[list1[i] + list2[i] for i in range(len(list1))]

#12


1  

This is simple with numpy.add()

使用numpi .add()很简单

import numpy

list1 = numpy.array([1, 2, 3])
list2 = numpy.array([4, 5, 6])
result = numpy.add(list1, list2) # result receive element-wise addition of list1 and list2
print(result)
array([5, 7, 9])

See doc here

看到医生

If you want to receiver a python list:

如果您想接收python列表:

result.tolist()

#13


0  

Although, the actual question does not want to iterate over the list to generate the result, but all the solutions that has been proposed does exactly that under-neath the hood!

虽然,实际的问题不希望遍历列表来生成结果,但是所有已经提出的解决方案都是在底层实现的!

To refresh: You cannot add two vectors without looking into all the vector elements. So, the algorithmic complexity of most of these solutions are Big-O(n). Where n is the dimension of the vector.

要刷新:如果不查看所有的向量元素,就不能添加两个向量。所以,这些解决方案的算法复杂度是大o (n)其中n是向量的维数。

So, from an algorithmic point of view, using a for loop to iteratively generate the resulting list is logical and pythonic too. However, in addition, this method does not have the overhead of calling or importing any additional library.

因此,从算法的角度来看,使用for循环迭代地生成结果列表也是符合逻辑的,也是符合python的。但是,此外,该方法没有调用或导入任何其他库的开销。

# Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]

The timings that are being showed/discussed here are system and implementation dependent, and cannot be reliable measure to measure the efficiency of the operation. In any case, the big O complexity of the vector addition operation is linear, meaning O(n).

这里显示/讨论的时间是与系统和实现相关的,不能作为衡量操作效率的可靠度量。无论如何,向量加法运算的O复杂度是线性的,意味着O(n)


推荐阅读
author-avatar
小妮子831020
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有