Python reduce函数作用及实例解析
作者:cnhkzyy 时间:2023-10-10 22:27:47
语法
在python3中,内置函数中已经没有reduce了。要使用reduce,需要从functools模块里引入
可以看到,reduce有三个参数,第一个是函数function,第二个是序列sequence,第三个是initial,为初始值,默认为None
作用
对序列中的元素进行累积
返回值
返回函数的计算结果
代码实例
from functools import reduce
from functools import reduce
def add(x, y):
return x + y
print(reduce(add, [1, 2, 3, 4, 5])) #计算过程 ((((1 + 2) + 3) + 4) + 5)
# 运行结果
15
在reduce中使用lambda函数
from functools import reduce
print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]))
# 运行结果
15
有初始值的情况,初始值为6
from functools import reduce
print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 6))
# 运行结果
21
#计算过程
6 + 1 = 7
7 + 2 = 9
9 + 3 = 12
12 + 4 = 16
16+ 5 = 21
来源:https://www.cnblogs.com/my_captain/p/12822732.html
标签:Python,reduce,函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Python爬虫的基本写法
2022-12-26 07:49:45
Python结合ImageMagick实现多张图片合并为一个pdf文件的方法
2021-01-28 20:36:55
![](https://img.aspxhome.com/file/2023/4/70744_0s.jpg)
PHP中round()函数对浮点数进行四舍五入的方法
2023-11-23 21:35:24
python基于Pandas读写MySQL数据库
2024-01-16 18:34:19
![](https://img.aspxhome.com/file/2023/1/78691_0s.png)
如何使用Python破解ZIP或RAR压缩文件密码
2022-03-24 19:28:45
![](https://img.aspxhome.com/file/2023/5/92055_0s.png)
laravel 5异常错误:FatalErrorException in Handler.php line 38的解决
2024-06-05 09:22:11
js下将字符串当函数执行的方法
2024-06-15 23:01:25
python3实现Dijkstra算法最短路径的实现
2023-10-14 13:17:40
![](https://img.aspxhome.com/file/2023/2/130662_0s.png)
Django 自定义404 500等错误页面的实现
2022-06-10 17:31:40
优化MySQL的数据库性能的八种方法
2012-01-05 19:28:53
详解python中的json的基本使用方法
2022-03-15 22:29:13
用Python删除本地目录下某一时间点之前创建的所有文件的实例
2021-07-29 05:34:59
python爬虫之自动登录与验证码识别
2022-05-18 07:22:53
el-input无法输入的问题和表单验证失败问题解决
2024-04-09 10:48:37
![](https://img.aspxhome.com/file/2023/7/139737_0s.png)
Vue项目中配置pug解析支持
2024-05-09 09:52:53
PHP在线打包下载功能示例
2024-06-05 09:40:17
![](https://img.aspxhome.com/file/2023/7/122527_0s.png)
Ubuntu下mysql与mysql workbench安装教程
2024-01-14 23:08:40
![](https://img.aspxhome.com/file/2023/9/102379_0s.jpg)
mysql存储过程详解
2024-01-25 22:28:15
解决Python对齐文本字符串问题
2021-08-20 10:22:26
Mysql中LAST_INSERT_ID()的函数使用详解
2024-01-16 06:50:32