How to add elements individually in tuple?

2019-02-28 17:08发布

问题:

How to add elements individually within the tuple?

For example, i need (2, 4) from (0,1) + (2,3), I've been doing it as such but is there a more pythonic / less verbose way to do the same?

>>> x = (0,1)
>>> y = (2,3)
>>> x + y
(0, 1, 2, 3)
>>> tuple(i+j for i,j in zip(x,y))
(2, 4)

回答1:

You can use zip and sum here:

Example:

>>> x = (0, 1)
>>> y = (2, 3)
>>> tuple(map(sum, zip(x, y)))
(2, 4)
  • zip lets us combine elements of two iterables or lists in pairs.
  • sum lets us sum the pairs
  • map lets us apply the sum function per pair.
  • finally we convert the resulting list (or iterable in Python 3.x) back into a tuple since that's what you seem to have wanted.

The above example basically ends up being;

(0 + 2, 1 + 3)


回答2:

Your own solution is the correct way to do that in pure python.

If you'd like to avoid the loop, you can vectorize the operation using numpy:

import numpy as np
tuple( np.asarray(tup1) + np.asarray(tup2) )

You should only convet the data back to a tuple if you really need it as a tuple. Otherwise, leave is as a numpy array, which means you can apply more vectorized operations to it later.

Also, the second conversion to np.asarray is optional. The first one would suffice (the other conversions are automatically done by numpy).