Prethia Prethia - 11 months ago 60
Python Question

Python 2.7 reduce lambda statement conversion to list comprehension

I was examining a code written in python but I got confused with the following line.

return ( reduce(lambda x, y: x + y[0],myList, 0)/len(Actions), )

This code takes x and y as an input sums x and y's first element. After that I think it reduces myList to the value of x+y[0] . How can I accomplish this with using list comprehension instead of using lambda.

Answer Source

The part that corresponds well to a list comprehension is what the reducing function does with its second argument y:

tmp = [ y[0] for y in myList ]

The reducing function then combines this list one element at a time with the "accumulator" x:

x = 0  # The third argument to reduce
tmp = [ y[0] for y in myList ]
for y in tmp:
    x += y

or more simply

x = 0
for y in myList:
    x += y[0]

or, as you have probably recognized by now

sum(y[0] for y in myList)