Samstag, 3. September 2011

Python 003: Summing specific items of nested lists

Say we're faced with the challenge of summing the last element of a list of nested lists.
An example might be

a=[[2,4,6],
[4,2,5],
[2,5,6]]

where we're interested in the sum of 6+5+6. In Python this can conveniently be done using the reduce/lambda pair of functions:

>>> reduce(lambda x,y: x+y, [i[-1] for i in a])
17
>>>

Keine Kommentare:

Kommentar veröffentlichen