reduce()函数的用法

Published on
18

reduce()函数介绍

from functools import reduce
result = reduce(function, iterable[, initializer])
  • function:接受两个参数的二元函数(如加法、乘法等)
  • iterable:待处理的可迭代对象(如列表、元组)
  • initializer(可选):初始值,若提供则计算从该值开始,否则使用可迭代对象的第一个元素

工作原理:

  1. 从可迭代对象中取出前两个元素,应用 function 得到一个结果;
  2. 将该结果与下一个元素继续应用 function,重复直至处理完所有元素

应用场景

(1)数值计算
  • 「1」求和
numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers)  # 输出 10
  • 「2」求最大最小值
max_value = reduce(lambda x,y:x if x >y  else y , [4, 5, 9, 1, 7])
(2)非数值操作
  • 「1」字符串拼接
words = ["Hello", " ", "world", "!"]
sentence = reduce(lambda x, y: x + y, words)  # 输出 "Hello world!"
  • 「2」字典值聚合
data = {'a': 1, 'b': 2, 'c': 3}
sum_values = reduce(lambda x, y: x + y, data.values()) # 输出 6

综合案例

求和

from functools import reduce

x = [i for i in range(10)]

print(reduce(lambda a, b: f"{a} + {b}", x),'=',reduce(lambda a,b:a+b,x))

输出: 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45


0