Python how to reduce multiple lists?

zs2020 picture zs2020 · Apr 7, 2011 · Viewed 16.5k times · Source

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?

Answer

antonakos picture antonakos · Apr 7, 2011

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)