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
You can, however, concatenate 2 or more tuples to form a new tuple. This is because tuples cannot be modified.
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() .
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.
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.
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]
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With