Python element-wise tuple operations like sum
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?
import operator
tuple(map(operator.add, a, b))
Using all built-ins..
tuple(map(sum, zip(a, b)))
This solution doesn't require an import:
tuple(map(lambda x, y: x + y, tuple1, tuple2))
from numpy import array
a = array( [1,2,3] )
b = array( [3,2,1] )
print a + b
gives array([4,4,4])
.
See http://www.scipy.org/Tentative_NumPy_Tutorial
Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple:
import operator
class stuple(tuple):
def __add__(self, other):
return self.__class__(map(operator.add, self, other))
# obviously leaving out checking lengths
>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)
Note: using self.__class__
instead of stuple
to ease subclassing.