Skip to content
Advertisement

Python how to reduce multiple lists?

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?

Advertisement

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)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement