0.摘要
本文主要介绍functool模块中的reduce函数,并使用reduce实现阶乘等操作。
1.reduce函数
官方释义:
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(lambda x,y:x+y,[1,2,3,4,5])计算了((((1 + 2)+(3)+ 4)+ 5)。如果初始值存在,那么在计算之前,它被放在所有项的前面。如果序列为空,它就作为默认值。
参数说明:
function:必选参数。需要有两个参数,并带有返回值
sequence:必选参数,但可以为空。列表,存放带计算的数据。如果为空,必须指定initial;如果不为空,允许存放[1,∞)个数。
initial:可选参数。如果指定,则作为第一个被使用的参数,相当于添加到sequence。如果sequence为空,则将initial设为默认的返回值(注意,空的意思是[],而不是None)。
比如:
def fun1(x,y):
return x + y
print(reduce(fun1,[],1))
由于sequence为空,所以print的值是initial的值,1。
另外:reduce函数仅支持位置实参,不支持关键字实参
所以,reduce(function=fun1,sequence=[1,2,3])这样的写法,会导致程序报错:
TypeError: reduce() takes no keyword arguments
2.程序示例
使用reduce函数实现阶乘:
from functools import reduce
def fun1(x,y):
return x*y
def factorial1(n):
sequence = range(1,n+1)
result = reduce(fun1,sequence,1)
return result
if __name__ == "__main__":
for i in range(10):
print(factorial1(i))
此处,添加initial是考虑到0!=1的情况。
当然,我们可以借助lambda函数使得程序更简单:
from functools import reduce
def factorial2(n):
result = reduce(lambda x,y:x*y, range(1,n+1),1)
return result
if __name__ == "__main__":
for i in range(10):
print(factorial2(i))
lambda表达式使用方法请移步: