I am able to use map
and sum
to achieve this functionality, but how to use reduce
?
There are 2 lists: a
, b
, they have same number of values. I want to calculate
a[0]*b[0]+a[1]*b[1]+...+a[n]*b[n]
The working version I wrote using map
is
value = sum(map(lambda (x,y): x*y, zip(a, b)))
How to use reduce
then? I wrote:
value = reduce(lambda (x,y): x[0]*y[0] + x[1]*y[1], zip(a, b)))
I got the error "TypeError: 'float' object is unsubscriptable
".
Can anyone shed some light on this?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With