<lambda>()缺少1个必需的位置参数:'z',涉及lambda和reduce。

3

我试图理解 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'
1个回答

3
functools.reduce需要一个有两个参数的函数。你不能将lambda x,y,z作为函数传递进去,因为它是一个带有三个参数的函数。(在Python中,使用错误数量的参数调用函数是错误的。functools.reduce将使用只有2个而不是3个参数的lambda x, y, z调用,因此会出现错误。)。
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).

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接