摘要:“Process from left to right, combining two values into one, until only a single value remains.”
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来文章 “刘心向学(45):functools.reduce —— 用一次遍历,把列表“压缩”成一个值”Share interest, spread happiness,
Increase knowledge, leave a beautiful!
Dear, this is LearningYard Academy.
Today, the editor brings you an article.
“Liu Xin Xiang Xue (45): functools.reduce — Collapse a List into a Single Value in One Pass”Welcome to your visit.
一、思维导图(Mind Map)
二、引言(Introduction)
Python 的 functools.reduce 来自函数式编程思想,它的名字来源于“归约”(reduction)操作 —— 将多个值逐步合并为一个。in Python comes from functional programming, and its name reflects the idea of reduction — collapsing multiple values into one.
它的核心思想是:
Its core idea is:
“从左到右,用一个函数把两个值变成一个,直到只剩一个。”
“Process from left to right, combining two values into one, until only a single value remains.”
"a" + "b" → "ab" + "c" → "abc"虽然 Python 内置了 sum、max 等专用函数,但 reduce 提供了通用的累积框架,适用于任何“两两合并”的场景。
While Python provides built-in functions like sum and max, reduce offers a general-purpose accumulation framework suitable for any “combine two into one” scenario.
三、基本语法(Basic Syntax)
: 接收两个参数的函数,返回一个结果: A two-argument function that returns a single result: 可迭代对象(如列表、元组)iterable: An iterable (e.g., list, tuple)initializer: 可选初始值。如果提供,它将作为第一次调用的“左操作数”initializer: Optional initial value. If provided, it becomes the first left operandAccumulation Process (e.g.,四、实战应用案例(Practical Application Examples)
1. 数值累积
Numeric Accumulation
2. 字符串拼接
String Concatenation
3. 布尔逻辑归约
Boolean Reduction
4. 列表展平
List Flattening
5. 字典合并
Dictionary Merging
dicts = [{'a': 1}, {'b': 2}, {'c': 3}]merged = reduce(lambda x, y: {**x, **y}, dicts, {})print(merged) # {'a': 1, 'b': 2, 'c': 3}6. 函数组合
Function Composition
五、高级技巧(Advanced Techniques)
1. 与 operator模块结合
Combine with the operatorModule
避免写 lambda,更简洁:
Avoid lambda for cleaner code:
from operator import
add, mul, or_, and_
total = reduce(add, [1,2,3,4,5])
# 15
product = reduce(mul, [1,2,3,4,5])
# 120
any_true = reduce(or_, [False, True])
# True
2. 处理空迭代器
Handle Empty Iterables
# 空列表 + 无初始值 → 抛出异常
# reduce(add, ) # TypeError
# 提供初始值可安全处理空列表
total = reduce(add, , 0)
# 0
六、注意事项(Handle Empty Iterables)
1. 可读性权衡
Readability Trade-offs
虽然 reduce 很强大,但过度使用会降低可读性:
While reduce is powerful, overuse harms readability:
# 不推荐:可读性差
result = reduce(lambda acc, x: acc.update({k: v for k, v in x.items if k in allowed}) or acc, dicts, {})
# 推荐:用普通循环或字典推导
原则:简单场景用 sum、any 等专用函数;复杂累积逻辑才用 reduce。
Rule of thumb
: Use specialized functions (sum, any) for simple cases; reserve reduce for complex accumulation logic.
2. 性能考虑
Performance Considerations
reduce
是 Python 函数调用,比 C 实现的 sum 慢。
对于大列表,避免使用 + 拼接列表或字符串(创建新对象)。
reduce
involves Python function calls — slower than C-optimized sum.Avoid using + to concatenate large lists or strings (creates new objects each time).
七、结语(Conclusion)
functools.reduce 是 Python 函数式编程的“瑞士军刀”。它不常被使用,但在需要通用累积逻辑时,它能提供无与伦比的表达力。
functools.reduce is the Swiss Army knife of functional programming in Python. Rarely used, yet unmatched in expressiveness when you need generic accumulation logic.
它教会我们一种思维方式:
It teaches a powerful mindset:
“如何把多个东西,一步步变成一个。”
“How to turn many things into one, step by step.”
从求和到函数组合,从展平到合并,reduce 展现了“抽象的力量”。
From summing numbers to composing functions, from flattening to merging, reduce showcases the power of abstraction.
正如计算机科学的核心思想:
As a core idea in computer science:
“Divide and Conquer.”
“Build abstractions.”
而 reduce,正是这种思想在数据处理中的优雅体现。
下次当你面对“把一堆东西合起来”的问题时,不妨问自己:
reduce is an elegant embodiment of these principles in data processing.
Next time you face a “combine many into one” problem, ask yourself:
“我能用 reduce 吗?”
“Can I use reduce?”
也许,答案是肯定的。
The answer might just be yes.
来源:春蕾教育