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)

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

你可能感兴趣的:(Python学习,python,reduce,第三个参数,学习)