什么是 reduce()?
reduce() 是 Python 中用于对序列进行累积操作的高阶函数。
它将一个二元函数(接受两个参数)反复应用于序列的元素,从左到右,最终将序列缩减为单个值。
在 Python 3 中,reduce() 不再是内置函数,需从 functools 模块导入:
from functools import reduce
基本语法
reduce(function, iterable[, initializer])
- function:一个接收两个参数的函数。
- iterable:要处理的序列(如列表、元组等)。
- initializer(可选):初始值。若提供,则作为第一次调用 function 的第一个参数。
实战示例
示例 1:计算列表元素之和
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) # 输出: 15
示例 2:求最大值
from functools import reduce
nums = [3, 7, 2, 9, 1]
max_val = reduce(lambda a, b: a if a > b else b, nums)
print(max_val) # 输出: 9
示例 3:字符串拼接
from functools import reduce
words = ['Hello', ' ', 'world', '!']
sentence = reduce(lambda x, y: x + y, words)
print(sentence) # 输出: Hello world!
交互演示
点击下方按钮,在浏览器中运行一个简单的 reduce 示例:
注意事项与替代方案
- 对于简单操作(如求和、求积),优先使用内置函数如
sum()或math.prod()(Python 3.8+)。 reduce()可读性有时较差,应权衡是否使用显式循环。- 空序列且未提供
initializer时会抛出TypeError。