python基础包的functools的reduce方法-亢保星

x33g5p2x  于2022-01-06 转载在 Python  
字(1.4k)|赞(0)|评价(0)|浏览(244)

#!/usr/bin/env python
#-- coding:utf-8 --
“”"

一 functools介绍

1、functools 模块可以说主要是为 函数式编程而设计,用于增强函数功能。
2、functools模块用以 为可调用对象(callable objects)定义高阶函数或操作。
3、functools下面包括:partial
update_wrapper doc
wraps
reduce map reduce
cmp_to_key
lru_cache
singledispatch

二 reduce 字面意思是归纳的意思

三 functools.reduce(function, iterable[, initializer])

方法名是reduce;
第一个参数是function
第二个参数是iterable : 可迭代的
第三个参数是:initializer:初始值;这个参数不是必须的。

四 函数作用:

apply function of two arguments cumulatively to the items of sequence,
这个方法有两个参数,可以对一个序列里面的元素进行累加。python中的序列可以是数组,元组,一切可以迭代的对象。
from left to right,
从 左到右
so as to reduce the sequence to a single value.
最后结果就是,把一个序列变成一个值
For example, calculates ((((1+2)+3)+4)+5).
“”"
from functools import reduce
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
“”"
x=1,y=2 计算结果:3
x=3,y=3 result:6
x=6,y=4 result:10
x=10,y=5 result:15
“”"
“”"
The left argument, x, is the accumulated value and
x 是累计的值
the right argument, y, is the update value from the sequence.
y 来自于序列,准备被累加到x上。
“”"
“”"
If the optional initializer is present,
如果可选的初始化参数存在:
it is placed before the items of the sequence in the calculation,
在计算过程中,他被放在序列的最前面。
and serves as a default when the sequence is empty.
如果序列为空的时候,可以作为默认值。
If initializer is not given and sequence contains only one item, the first item is returned.
如果初始值没有给定,同时队列中只有一个值,那这个值将被返回。
下面是reduce的源码:
“”"
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

相关文章