How to add elements individually in tuple?

蓝咒 提交于 2019-12-02 07:24:17
James Mills

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)

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!