Python element-wise tuple operations like sum Ask Question

Python element-wise tuple operations like sum Ask Question

Is there anyway to get tuple operations in Python to work like this:

>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)

instead of:

>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)

I know it works like that because the __add__ and __mul__ methods are defined to work like that. So the only way would be to redefine them?

ベストアンサー1

Using all built-ins..

tuple(map(sum, zip(a, b)))

おすすめ記事