reduce python3_python-reduce函数

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表达式使用方法请移步:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值