<lambda>() 缺少 1 个必需的位置参数:'z' 使用 lambda 和 reduce

<lambda>() missing 1 required positional argument: 'z' with lambda and reduce

我试图了解 lambdareduce() 的工作原理。我尝试了这些示例,但无法理解为什么这会给我错误。有人可以解释一下它是如何执行的吗?

>>> 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).