How can I pairwise sum two equal-length tuples [duplicate]
How can I get the pairwise sum of two equal length tuples? For example if I h开发者_Go百科ave (0,-1,7) and (3,4,-7) I would like to have (3,3,0) as answer.
tuple(map(lambda (x, y): x + y, zip((0,-1,7), (3,4,-7))))
If you prefer to avoid map
and lambda
then you can do:
tuple(x + y for x,y in zip((0,-1,7), (3,4,-7)))
EDIT: As one of the answers pointed out, you can use sum instead of explicitly splitting the tuples returned by zip
. Therefore you can rewrite the above code sample as shown below:
tuple(sum(t) for t in zip((0,-1,7), (3,4,-7)))
Reference: zip
, map
, sum
.
Use sum():
>>> tuple(sum(pair) for pair in zip((0,-1,7), (3,4,-7)))
or
>>> tuple(map(sum, zip((0,-1,7), (3,4,-7))))
>>> t1 = (0,-1,7)
>>> t2 = (3,4,-7)
>>> tuple(i + j for i, j in zip(t1, t2))
(3, 3, 0)
Alternatively (good if you have very big tuples or you plan to do other mathematical operations with them):
> import numpy as np
> t1 = (0, -1, 7)
> t2 = (3, 4, -7)
> at1 = np.array(t1)
> at2 = np.array(t2)
> tuple(at1 + at2)
(3, 3, 0)
Cons: more data preparation is needed. Could be overkill in most cases.
Pros: operations are very explicit and isolated. Probably very fast with big tuples.
精彩评论