Warren Daza
Warren Daza

Reputation: 41

Math Operation on List of numbers

I was wondering if it's possible to do mathematical operation between lists of numerical variables? For example, I have..

pointA = [ 22, 44, 83 ]
pointB = [ -17, 11, -25 ]

pointC = pointA - pointB
#result: [ 5, 55, 61 ]

Or should I just create my own function? Thank you!

Upvotes: 1

Views: 7105

Answers (5)

JeremyFromEarth
JeremyFromEarth

Reputation: 14344

I've been working on a linear algebra module in Python that could be used for this. It is lightweight and easy to use. The add() method allows you to add a list of matrices, in the event that you want to add more than two points.

Check it out here: https://github.com/jeremynealbrown/mbyn

A = [
            [8, 3, 4],
            [21, 3, 7],
            [3, 5, 2]
    ]

B = [
            [5, 3, 1], 
            [1, 9, 4],
            [3, 6, 1]
    ]

mbyn.add([A, B])

#output
#13, 6, 5
#22, 12, 11
#6, 11, 3

Upvotes: 0

Beni Cherniavsky-Paskin
Beni Cherniavsky-Paskin

Reputation: 10039

Install numpy.

>>> import numpy
>>> numpy.add([ 22, 44, 83 ], [ -17, 11, -25 ])
array([ 5, 55, 58])

array objects are mostly list-compatible, but are much more powerful.

>>> pointA = numpy.array([ 22, 44, 83 ])
>>> pointB = numpy.array([ -17, 11, -25 ])
>>> pointA + pointB
array([ 5, 55, 58])
>>> pointA * pointB
array([ -374,   484, -2075])
>>> pointA.dot(pointB)
-1965

Supports tons of other operations, matrices and multi-dimentional arrays...

Upvotes: 5

root
root

Reputation: 80346

Something like this perhaps:

In [1]: def calculate(p1, p2):
   ...:     return map(sum, zip(p1, p2))

In [2]: pointA = [ 22, 44, 83 ]
   ...: pointB = [ -17, 11, -25 ]

In [3]: calculate(pointA, pointB)
Out[3]: [5, 55, 58]

Upvotes: 1

Tim Heap
Tim Heap

Reputation: 1711

This can be done with map:

pointC = map(lambda p1, p2: p1 + p2, pointA, pointB)

or, more simply:

from operators import add
pointC = map(add, pointA, pointB)

Upvotes: 4

schesis
schesis

Reputation: 59128

You're adding, not subtracting, to get that result ... anyway, list comprehensions and zip() will give you what you want:

>>> pointA = [22, 44, 83]
>>> pointB = [-17, 11, -25]
>>> pointC = [a + b for a, b in zip(pointA, pointB)]
>>> pointC
[5, 55, 58]

Upvotes: 4

Related Questions