【Python】functools模块reduce方法
xixuefeng
Python
2018-03-17 22:50:23
1,000 次浏览
functools, reduce
【Python】functools模块reduce方法已关闭评论
functools — Higher-order functions and operations on callable objects
用于高阶函数:指那些作用于函数或者返回其它函数的函数,通常只要是可以被当做函数调用的对象就是这个模块的目标。
1:语法:
1 |
functools.reduce(function, iterable[, initializer]) |
2:大致是这个意思(摘自官方文档)
1 2 3 4 5 6 7 8 9 |
def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: value = next(it) else: value = initializer for element in it: value = function(value, element) return value |
3:用例题解释这个函数
1 2 3 4 5 6 |
>>> from functools import * >>> >>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 15 >>> ## 这个结果等价于 ((((1+2)+3)+4)+5) |
4:我们看语法上还有一个初始化的值,是可选项,默认值None,以下例题传入一个值10
1 2 3 4 5 |
>>> from functools import * >>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5],10) 25 >>> ## 这个结果等价于 ((((1+2)+3)+4)+5)+10 |