所需模块:functools
所需函数:reduce()
reduce函数如何使用呢?
首先在python的IDLE中输入import functools,按下回车,导入functools模块
然后输入help(functools.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.
reduce()函数的第一个参数是一个含有两个自变量的函数,第二个参数是一个序列,可选参数是初始值(initial)
文档的例子中用lambda关键字定义了一个含有两个自变量x,y的匿名函数,返回结果是x+y。
reduce函数会把该函数依次作用到列表[1,2,3,4,5]的各个元素上面,将结果进行累加,把累加结果返回。
总之reduce函数可以连续不断的对序列中元素逐次进行相同的函数操作,可以