Python内置函数reduce的第三个参数

Python内置函数reduce的第三个参数

原来以为reduce只有两个参数,今天在看别人代码的时候看到传了第三个参数,结合官方文档终于搞明白了

看一下官方的说明:

Help on built-in function reduce in module _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.

官方文档首先介绍了一下函数功能,将一个有两个参数的函数从左到右作用在一个序列上,值累积后减少到一个值。
然后介绍了第三个参数,有两个作用:
一是如果初始值存在,那它应该放置在序列的前面,然后参与运算;也就是说第三个参数将做为运算时的第一个参数传入进行计算;
二是当结果为空时作为默认值。

用一个简单的例子增强理解:

from functools import reduce
a = reduce(lambda x,y:x * y , [1],2)
b = reduce(lambda x,y:x * y , [2,2,3],3)
c = reduce(lambda x,y:x * y , [1,2,3,5,6],0)
d = reduce(lambda x,y:x * y , [ ],5)
print(a,b,c,d)

输出结果如下:
在这里插入图片描述

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值