Python reduce()


1. 描述

reduce() 对参数序列中元素进行累积。

函数将一个数据集合(元组、列表等)中的所有数据进行下列操作:对集合中的第1、2个元素进行function(两个参数)运算,得到的结果再与第3个元素进行 function() 运算。


Python3 reduce()被移到 functools 模块。

from functools import reduce

2. 语法

reduce(function, iterable[, initializer])

参数

  • function:两个参数
  • iterable:可迭代对象
  • initializer:可选,初始参数

返回值

函数计算结果。


3. 实例

from functools import reduce

def add(x, y):
    return x+y
sum1 = reduce(add, (1, 2 ,3 ,4 ,5))
sum2 = reduce(lambda x, y: x+y, [1, 2, 3 ,4 ,5])
print(sum1)
print(sum2)

计算结果:

15
15
原文地址:https://www.cnblogs.com/keye/p/15596741.html