摘要:Python 的 functools.reduce 来自函数式编程思想,它的名字来源于“归约”(reduction)操作 —— 将多个值逐步合并为一个。
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是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.
Python 的 functools.reduce 来自函数式编程思想,它的名字来源于“归约”(reduction)操作 —— 将多个值逐步合并为一个。
functools.reduce
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.”
比如:
For example:
虽然 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.
from functools import reducereduce(function, iterable[, initializer])function
: 接收两个参数的函数,返回一个结果
function
: A two-argument function that returns a single result
iterable
: 可迭代对象(如列表、元组)
iterable
: An iterable (e.g., list, tuple)
initializer
: 可选初始值。如果提供,它将作为第一次调用的“左操作数”
initializer
: Optional initial value. If provided, it becomes the first left operand
Accumulation Process (e.g., reduce(add, [1,2,3])):
第一次:add(1, 2) → 3
First: add(1, 2) → 3
第二次:add(3, 3) → 6
结果:6
Result: 6
如果提供 initializer=10:
With initializer=10:
from functools import reduce# 求和(等价于 sum)total = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]) # 15# 乘积(等价于 math.prod in Python 3.8+)product = reduce(lambda x, y: x * y, [1, 2, 3, 4, 5]) # 120# 阶乘factorial = reduce(lambda x, y: x * y, range(1, 6), 1) # 120words = ['Hello', 'World', 'Python']sentence = reduce(lambda x, y: x + ' ' + y, words)print(sentence) # "Hello World Python"# all 的等价实现bools = [True, True, False]all_true = reduce(lambda x, y: x and y, bools, True) # False# any 的等价实现any_true = reduce(lambda x, y: x or y, bools, False) # Truenested = [[1, 2], [3, 4], [5]]flat = reduce(lambda x, y: x + y, nested, )print(flat) # [1, 2, 3, 4, 5]# 注意:对于大列表,x + y 创建新列表,性能较差。建议用 itertools.chain。5. 字典合并Dictionary Mergingdicts = [{'a': 1}, {'b': 2}, {'c': 3}]merged = reduce(lambdax, y: {**x, **y}, dicts, {})print(merged) # {'a': 1, 'b': 2, 'c': 3}6. 函数组合Function Composition# 将多个函数组合成一个:f(g(h(x)))defcompose(*funcs):returnlambda x: reduce(lambda acc, f: f(acc), reversed(funcs), x)# 示例:先转大写,再反转defto_upper(s):return s.upperdefreverse(s):return s[::-1]pipeline = compose(to_upper, reverse)print(pipeline("hello")) # "OLLEH"Avoid lambda for cleaner code:
from
operator import add, mul, or_, and_total = reduce(add, [1,2,3,4,5]) # 15product = reduce(mul, [1,2,3,4,5]) # 120any_true = reduce(or_, [False, True]) # True
Python深色版本# 空列表 + 无初始值 → 抛出异常# reduce(add, ) # TypeError# 提供初始值可安全处理空列表total = reduce(add, , 0) # 0虽然 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.
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).
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.
“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.
今天的分享就到这里了。
如果您对文章有独特的想法,
欢迎给我们留言,
让我们相约明天。
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
参考资料:通义千问
参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.
Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.
本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!
LearningYard新学苑
文字:song
排版:song
审核|qiu
来源:LearningYard学苑