Python how to reduce multiple lists?
The first argument of the lambda function is the sum so far and the second argument is the next pair of elements:
value = reduce(lambda sum, (x, y): sum + x*y, zip(a, b), 0)
A solution using reduce
and map
,
from operator import add,mul
a = [1,2,3]
b = [4,5,6]
print reduce(add,map(mul,a,b))
I would do it this way (I don't think you need lambda)...
sum(x*y for x, y in zip(a, b))
This also seems slightly more explicit. Zip AB, multiply them, and sum up the terms.