具有常规功能的 Reduce()
Reduce() with a regular function
我想使用 reduce() 和一个常规函数计算两个列表的乘积和。
正则函数对return产品定义为:
def func(maturity, weight):
return maturity * weight
减少函数如下:
reduce(func, zip(terms, weights))
一个错误
"TypeError: can't multiply sequence by non-int of type 'tuple'"
然后出现。有没有办法通过常规函数而不是lambda来计算两个列表的乘积和?
我认为您误解了 reduce
的用法。它所做的是在向量上重复应用一个操作以产生一个标量作为最终结果。您要做的是在不相关的单独元素上应用相同的功能。为此,您需要 map
:
out = map(func, terms, weights)
正如乔恩·克莱门茨 (Jon Clements) 指出的那样,如果您的函数像逐元素乘法一样简单,您可以考虑改用 operator.mul
:
import operator
out = map(operator.mul, terms, weights)
错误是因为你在乘法元组,
func
中的两个参数都是元组,看起来像这样
('A', 1), ('B', 2)
如果您采用索引 1 上的元素,它将起作用。
def func(maturity, weight):
return maturity[1] * weight[1]
terms = ['A', 'B', 'C']
weights = [1, 2]
reduce(func, zip(terms, weights))
我想使用 reduce() 和一个常规函数计算两个列表的乘积和。
正则函数对return产品定义为:
def func(maturity, weight):
return maturity * weight
减少函数如下:
reduce(func, zip(terms, weights))
一个错误
"TypeError: can't multiply sequence by non-int of type 'tuple'"
然后出现。有没有办法通过常规函数而不是lambda来计算两个列表的乘积和?
我认为您误解了 reduce
的用法。它所做的是在向量上重复应用一个操作以产生一个标量作为最终结果。您要做的是在不相关的单独元素上应用相同的功能。为此,您需要 map
:
out = map(func, terms, weights)
正如乔恩·克莱门茨 (Jon Clements) 指出的那样,如果您的函数像逐元素乘法一样简单,您可以考虑改用 operator.mul
:
import operator
out = map(operator.mul, terms, weights)
错误是因为你在乘法元组,
func
中的两个参数都是元组,看起来像这样
('A', 1), ('B', 2)
如果您采用索引 1 上的元素,它将起作用。
def func(maturity, weight):
return maturity[1] * weight[1]
terms = ['A', 'B', 'C']
weights = [1, 2]
reduce(func, zip(terms, weights))