Parameter Details
function 用于递归可迭代对象的函数(必须接受两个参数)。(positional-only)
iterable 要被递归的可迭代对象。(positional-only)
initializer 递归的起始值。(可选,仅限位置)

Section 68.1: 概述

# No import needed

# No import required...
from functools import reduce # ... but it can be loaded from the functools module

from functools import reduce # mandatory

reduce 通过在可迭代元素的下一个元素上重复应用一个函数来减少可迭代元素,并减少迄今为止的累计结果。 到目前为止的累积结果。

def add(s1, s2):
  return s1 + s2

asequence = [1, 2, 3]

reduce(add, asequence) # equivalent to: add(add(1,2),3)
# Out: 6

概述

在本例中,我们定义了自己的 add 函数。然而,Python 在 operator 模块中提供了一个标准的等价函数:

import operator
reduce(operator.add, asequence)
# Out: 6

reduce 也可以传递一个起始值:

reduce(add, asequence, 10)
# Out: 16

概述

Section 68.2: 使用递归

def multiply(s1, s2):
  print('{arg1} * {arg2} = {res}'.format(arg1=s1, arg2=s2, res=s1*s2))
  return s1 * s2

asequence = [1, 2, 3]

在给定初始化器的情况下,函数通过将其应用于初始化器和第一个可迭代元素而启动:

cumprod = reduce(multiply, asequence, 5)
# Out: 5 * 1 = 5
# 5 * 2 = 10
# 10 * 3 = 30
print(cumprod)
# Out: 30

在没有初始化参数的情况下,reduce 会首先对前两个列表元素应用函数:

cumprod = reduce(multiply, asequence)
# Out: 1 * 2 = 2
# 2 * 3 = 6
print(cumprod)
# Out: 6

使用递归

Section 68.3: 累积

import operator
reduce(operator.mul, [10, 5, -3])
# Out: -150

累积

Section 68.4: 任何/所有非短路变量

reduce 不会在可迭代对象被完全迭代之前终止迭代,因此它可以用来创建一个非短路的 any() 或 all() 函数:

import operator
# non short-circuit "all"
reduce(operator.and_, [False, True, True, True]) # = False

# non short-circuit "any"
reduce(operator.or_, [True, False, False, False]) # = True

任何/所有非短路变量