Pythonic way to sum n-th list element?
Guy Middleton
guy at obstruction-no-spam.com
Fri Apr 18 16:21:08 EDT 2003
What is the most Pythonic way to sum the n-th element of a list of lists (or
of tuples)?
The obvious (to me) way is to use reduce, a list comprehension, and a lambda:
$ python
Python 2.2.1 (#1, Jul 4 2002, 15:23:46)
[GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> x = (("a", 1), ("b", 2), ("c", 3))
>>> # want to sum 1+2+3 = 6
...
>>> reduce(lambda a, b: a+b, [y[1] for y in x])
6
>>>
$
But I don't really like lambda, is there a better way to do this?
-Guy
More information about the Python-list
mailing list