一、Python标准库模块functools:reduce()函数
reduce()函数在Python的标准库模块functools中,其基本语法如下:
sequence:序列对象
initializer:可选,初始参数
二、举例说明
1.第一种情况:不带初始参数
当没有初始参数时,reduce()函数形式为:
代码如下(示例):
from functools import reduce
def add(x,y):
return x+y
a = reduce(add, [1, 2, 3, 4, 5]) #计算列表和
print(a)
结果如下(示例):
15
2.第二种情况:带初始参数
当有初始参数时,reduce()函数形式为:
代码如下(示例):
from functools import reduce
a = reduce(lambda x, y: x + y, [2, 3, 4, 5, 6], 1)
print(a)
结果如下(示例):
21