What is the most pythonic way of adding the values of two or more tuples to produce a total for each ‘column’?
Eg:
>>> a = (10, 20)
>>> b = (40, 50)
>>> c = (1, 3)
>>> ???
(51, 73)
I’ve so far considered the following:
def sumtuples(*tuples):
return (sum(v1 for v1,_ in tuples), sum(v2 for _,v2 in tuples))
>>> print sumtuples(a, b, c)
(51, 73)
I’m sure this far from ideal – how can it be improved?
I guess you could use
reduce, though it’s debatable whether that’s pythonic ..Here’s another way using
mapandzip:or, if you’re passing your collection of tuples in as a list:
and, using a list comprehension instead of
map: