Python reduce函数作用及实例解析
2020-05-09 04:06
961 查看
语法
在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
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- Python input函数使用实例解析
- python迭代和解析(3):range、map、zip、filter和reduce函数
- Python嵌套函数,作用域与偏函数用法实例分析
- Python学习笔记之函数的定义和作用域实例详解
- python高阶函数map()和reduce()实例解析
- 深入解析Python中函数的参数与作用域
- Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法实例分析
- Python嵌套函数,作用域与偏函数用法实例分析
- Python中的高级函数map/reduce使用实例
- 实例详解python函数的对象、函数嵌套、名称空间和作用域
- python中set()函数简介及实例解析
- 深入解析Python中函数的参数与作用域
- python filter()、map()、reduce()函数解析
- Python zip函数打包元素实例解析
- python 魔法函数实例及解析
- Python urlencode和unquote函数使用实例解析
- 使用Python中的reduce()函数求积的实例
- Python中的random.uniform()函数教程与实例解析
- python误差棒图errorbar()函数实例解析
- Python lambda表达式filter、map、reduce函数用法解析