Siyu Zhuang Siyu Zhuang - 2 months ago 21
Python Question

Reduce() with a regular function

I want to calculate the product sum of two lists using reduce() and a regular function.

The regular function to return the product is defined as:

def func(maturity, weight):
return maturity * weight


and the reduct function is like:

reduce(func, zip(terms, weights))


An error

"TypeError: can't multiply sequence by non-int of type 'tuple'"


then appears. Is there any way to pass the regular function instead of lambda to calculate the product sum of the two lists?

Answer Source

I think you're mis-understanding the use of reduce. What it does is apply an operation repeatedly on a vector to produce a scalar as the end result. What you want to do is apply the same function on separate elements which are not related. For that purpose, you need map:

out = map(func, terms, weights)

As Jon Clements noted, if your function is as simple as element-wise multiplication, you might consider using operator.mul instead:

import operator
out = map(operator.mul, terms, weights)