首页 > 解决方案 > 为什么减少要求参数的函数

问题描述

我已经用 reduce 内置函数编写了这些代码行,但它显示给定参数的错误。

错误

TypeError Traceback (last last call last) in 4 5 lst = [1,2,3] ----> 6 reduce(d_n, lst)

TypeError: d_n() 接受 1 个位置参数,但给出了 2 个


from functools import reduce
def d_n(digit):
    return(digit)

lst = [1,2,3]
reduce(d_n, lst)

标签: python-3.x

解决方案


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).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

关键点:两个参数的函数

您的d_n()函数只接受一个参数,这使得它与reduce


推荐阅读