Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
zs2020 Avatar asked Apr 07 '11 13:04

zs2020


1 Answers

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)
like image 170
antonakos Avatar answered Oct 12 '22 21:10

antonakos