【问题标题】:Why reduce function asking for arguments为什么减少要求参数的函数
【发布时间】:2019-09-10 14:00:58
【问题描述】:

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

错误

TypeError Traceback(最近一次调用最后一次) 在 4 5 lst = [1,2,3] ----> 6 减少(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


【解决方案1】:
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 不兼容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2012-01-30
    • 2018-04-16
    • 2019-07-28
    • 2017-12-27
    • 2020-10-11
    相关资源
    最近更新 更多