【发布时间】:2018-02-05 08:30:53
【问题描述】:
我想使用 reduce() 和一个常规函数来计算两个列表的积和。
返回产品的常规函数定义为:
def func(maturity, weight):
return maturity * weight
而归约函数是这样的:
reduce(func, zip(terms, weights))
一个错误
"TypeError: can't multiply sequence by non-int of type 'tuple'"
然后出现。有没有办法通过正则函数而不是lambda来计算两个列表的乘积和?
【问题讨论】:
-
您能否将您的问题格式化为更具可读性?并举例说明
terms和weights的外观。 -
看起来像你想要的:
map(func, terms, weights)... 在这种情况下 - 如果你的函数不仅仅是乘法,你可以使用内置函数,例如:result = map(operator.mul, terms, weights) -
对于糟糕的格式真的很抱歉。我尝试按照说明缩进代码,但代码并没有以一种简洁的方式显示。
-
我明白了!我误解了 reduce 的工作原理。我应该使用 map 来获取产品列表,然后他们使用 reduce 来总结它们。
-
@SiyuZhuang:用
sum总结一下!
标签: python python-2.7 function reduce callable