Pythonic way to sum n-th list element?
Skip Montanaro
skip at pobox.com
Fri Apr 18 16:33:45 EDT 2003
Guy> What is the most Pythonic way to sum the n-th element of a list of
Guy> lists (or of tuples)?
Guy> The obvious (to me) way is to use reduce, a list comprehension, and
Guy> a lambda:
...
Guy> But I don't really like lambda, is there a better way to do this?
You can use the add function in the operator module:
>>> import operator
>>> x = (("a", 1), ("b", 2), ("c", 3))
>>> reduce(operator.add, [y[1] for y in x], 0)
6
Skip
More information about the Python-list
mailing list