Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

python - Adding two tuples elementwise

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...