zsong - 1 month ago 4x

Python Question

Hi I am able to use

`map`

`sum`

`reduce`

There are 2 lists:

`a`

`b`

`a[0]*b[0]+a[1]*b[1]+...+a[n]*b[n]`

The working version I wrote using

`map`

`value = sum(map(lambda (x,y): x*y, zip(a, b)))`

How to use

`reduce`

`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? Thanks in advance!

Answer

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)
```

Source (Stackoverflow)

Comments