Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two tuples elementwise

Tags:

I was just wondering if there was an especially pythonic way of adding two tuples elementwise?

So far (a and b are tuples), I have

map(sum, zip(a, b))

My expected output would be:

(a[0] + b[0], a[1] + b[1], ...)

And a possible weighing would be to give a 0.5 weight and b 0.5 weight, or so on. (I'm trying to take a weighted average).

Which works fine, but say I wanted to add a weighting, I'm not quite sure how I would do that.

Thanks

like image 444
James Avatar asked May 14 '13 16:05

James


People also ask

Can you add 2 tuples together?

You can, however, concatenate 2 or more tuples to form a new tuple. This is because tuples cannot be modified.

How do you sum two tuples?

Method #2 : Using map() + zip() + sum() The combination of above functions can also be used to achieve this particular task. In this, we add inbuilt sum() to perform summation and zip the like indices using zip() and extend logic to both tuples using map() .

How do you find the sum of two tuples in Python?

To find a sum of the tuple in Python, use the sum() method. Define a tuple with number values and pass the tuple as a parameter to the sum() function; in return, you will get the sum of tuple items.

Can you add a tuple to a tuple?

You can combine tuples to form a new tuple. The addition operation simply performs a concatenation with tuples. You can only add or combine same data types. Thus combining a tuple and a list gives you an error.


2 Answers

Zip them, then sum each tuple.

[sum(x) for x in zip(a,b)]

EDIT : Here's a better, albeit more complex version that allows for weighting.

from itertools import starmap, islice, izip

a = [1, 2, 3]
b = [3, 4, 5]
w = [0.5, 1.5] # weights => a*0.5 + b*1.5

products = [m for m in starmap(lambda i,j:i*j, [y for x in zip(a,b) for y in zip(x,w)])]

sums = [sum(x) for x in izip(*[islice(products, i, None, 2) for i in range(2)])]

print sums # should be [5.0, 7.0, 9.0]
like image 143
Chris Doggett Avatar answered Oct 05 '22 04:10

Chris Doggett


If you do not mind the dependency, you can use numpy for elementwise operations on arrays

>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.array([3, 4, 5])
>>> a + b
array([4, 6, 8])
like image 36
D R Avatar answered Oct 05 '22 02:10

D R