How to add elements individually in tuple?

北城以北 提交于 2019-12-02 07:25:41

问题


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



来源:https://stackoverflow.com/questions/24969391/how-to-add-elements-individually-in-tuple

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