python - Adding two tuples elementwise -


i wondering if there pythonic way of adding 2 tuples elementwise?

so far (a , b tuples), have

map(sum, zip(a, b)) 

my expected output be:

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

and possible weighing give 0.5 weight , b 0.5 weight, or on. (i'm trying take weighted average).

which works fine, wanted add weighting, i'm not quite sure how that.

thanks

zip them, sum each tuple.

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

edit : here's better, albeit more complex version allows weighting.

from itertools import starmap, islice, izip  = [1, 2, 3] b = [3, 4, 5] w = [0.5, 1.5] # weights => a*0.5 + b*1.5  products = [m m in starmap(lambda i,j:i*j, [y x in zip(a,b) y in zip(x,w)])]  sums = [sum(x) x in izip(*[islice(products, i, none, 2) in range(2)])]  print sums # should [5.0, 7.0, 9.0] 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -