python-3.x - 为什么减少要求参数的函数
问题描述
我已经用 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)
解决方案
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
推荐阅读
- python - 如何声明指向同一对象/引用的静态属性
- mediawiki - MediaWiki 模板:通知导入看起来与 mediawiki 不同
- javascript - 反应子组件不从父值渲染道具
- javascript - Javascript:计算时差不会返回任何问题
- json - django ajax 内容安全策略指令
- jupyter-notebook - 风筝不在 jupyter 实验室工作,但在 python 工作
- php - PHP & Bootstrap 3 sendmail.php 确认进入引导提示成功或失败消息
- powershell - 添加“获取模块 | 移除模块;Clear-Host' 到包含的 PowerShell 代码
- reactjs - 如何解决 React js 中的解析错误?
- java - 我可以在springboot中轻松重用url路径映射作为设置吗?