我试图了解 lambda
和 reduce()
是如何工作的。我尝试了这些示例,但无法理解为什么这会给我错误。有人可以解释一下它是如何执行的吗?
>>> functools.reduce(lambda x,y:x+y, range(10))
45
这很好用。但是当我尝试这个时,它给了我错误:
>>> functools.reduce(lambda x,y,z:x+y+z, range(10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'z'
最佳答案
functools.reduce
需要一个有两个参数的函数。
您不能将 lambda x, y, z
作为函数传递,因为它是 3 个参数的函数。
(在 Python 中,使用错误数量的参数调用函数是错误的。functools.reduce
将调用 lambda x, y, z
,仅使用 2 个参数而不是 3 个参数,所以这是一个错误。)
来自 help(functools.reduce)
:
reduce(...) reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
关于python - <lambda>() 缺少 1 个必需的位置参数 : 'z' with lambda and reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47493642/