Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise vector adding in Python? [duplicate]

Tags:

python

I often do vector addition of Python lists.

Example: I have two lists like these:

a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] 

I now want to add b to a to get the result a = [3.0, 5.0, 7.0].

Usually I end up doing like this:

a[0] += b[0] a[1] += b[1] a[2] += b[2] 

Is there some efficient, standard way to do this with less typing?

UPDATE: It can be assumed that the lists are of length 3 and contain floats.

like image 379
Johan Kotlinski Avatar asked May 10 '09 11:05

Johan Kotlinski


People also ask

How do you sum two vectors in Python?

Vector Addition We can add vectors directly in Python by adding NumPy arrays. The example defines two vectors with three elements each, then adds them together. Running the example first prints the two parent vectors then prints a new vector that is the addition of the two vectors.

How do you find the sum of a vector?

The triangle law of the addition of vectors states that two vectors can be added together by placing them together in such a way that the first vector's head joins the tail of the second vector. Thus, by joining the first vector's tail to the head of the second vector, we can obtain the resultant sum vector.

How do you add vectors?

To add or subtract two vectors, add or subtract the corresponding components. Let →u=⟨u1,u2⟩ and →v=⟨v1,v2⟩ be two vectors. The sum of two or more vectors is called the resultant. The resultant of two vectors can be found using either the parallelogram method or the triangle method .


2 Answers

If you need efficient vector arithmetic, try Numpy.

>>> import numpy >>> a=numpy.array([0,1,2]) >>> b=numpy.array([3,4,5]) >>> a+b array([3, 5, 7]) >>>  

Or (thanks, Andrew Jaffe),

>>> a += b >>> a array([3, 5, 7]) >>>  
like image 53
gimel Avatar answered Sep 28 '22 00:09

gimel


I don't think you will find a faster solution than the 3 sums proposed in the question. The advantages of numpy are visible with larger vectors, and also if you need other operators. numpy is specially useful with matrixes, witch are trick to do with python lists.

Still, yet another way to do it :D

In [1]: a = [1,2,3]  In [2]: b = [2,3,4]  In [3]: map(sum, zip(a,b)) Out[3]: [3, 5, 7] 

Edit: you can also use the izip from itertools, a generator version of zip

In [5]: from itertools import izip  In [6]: map(sum, izip(a,b)) Out[6]: [3, 5, 7] 
like image 21
besen Avatar answered Sep 28 '22 01:09

besen