
reduce 是 Python 中一个用于累积计算的函数,它会把一个序列中的元素,通过指定的函数,逐步归纳成一个单一的结果。
它和 map、filter 一样,是函数式编程的经典工具。
一、基本用法
reduce 函数的语法:
from functools import reduce
reduce(function, iterable[, initializer])
-
function:接收两个参数的函数,用于累积计算 -
iterable:可迭代对象 -
initializer(可选):初始值
示例 1:计算总和
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers)
print(result) # 15
# 执行过程:
# x=1, y=2 → 3
# x=3, y=3 → 6
# x=6, y=4 → 10
# x=10, y=5 → 15
示例 2:指定初始值
from functools import reduce
numbers = [1, 2, 3]
result = reduce(lambda x, y: x + y, numbers, 10)
print(result) # 16(10 + 1 + 2 + 3)
# 执行过程:
# x=10, y=1 → 11
# x=11, y=2 → 13
# x=13, y=3 → 16
二、reduce vs 其他方式
1. reduce vs 循环
# 用循环计算乘积
numbers = [1, 2, 3, 4, 5]
product = 1
for n in numbers:
product *= n
# 用 reduce
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
2. reduce vs sum()
对于求和,sum() 是更好的选择:
# 不推荐:sum 已经内置了
reduce(lambda x, y: x + y, numbers)
# 推荐
sum(numbers)
3. reduce vs functools.accumulate
accumulate 返回中间结果 ,reduce 只返回最终结果:
from itertools import accumulate
# accumulate 返回每一步的累积结果
print(list(accumulate([1, 2, 3, 4]))) # [1, 3, 6, 10]
# reduce 只返回最终结果
print(reduce(lambda x, y: x + y, [1, 2, 3, 4])) # 10
reduce 就是把一个序列累积成一个值的工具,建议在 sum、max、min 等内置函数不适用时再考虑它,日常开发更多用 for 循环来保持代码清晰。