usage of reduce

Nick Perkins nperkins7 at home.com
Tue May 8 02:32:39 EDT 2001


>>> z
[(1,5),(2,6),(3,7)]

>>> reduce(lambda x,y: x[1]+y[1], z)

....error..

This does not work because your lambda takes two tuples,
and returns one number.
The function used in a reduce must return the same type
of value as it takes.  It needs to use the result as
one of the arguments to the next call of the function.

try:
reduce(lambda x,y: x+y, map(lambda tup: tup[1], z))

This will first call map to produce a list consisting
of the [1] part of each tuple,
then reduce that list with the addition lambda.







More information about the Python-list mailing list