实现说明
total、squares 定义在模块顶层,中间不经过函数作用域。
使用要点
- 跑完文件,输出里会留下标记——
empty init :。
常见问题
包管理器会看到什么?
一份空的依赖清单。示例没有需要抓取的导入。 文件用顶层绑定保存自己的状态:total、squares。
核心语句
except TypeError as exc:
print('empty :', exc)
代码示例
import functools
import operator
# reduce 把二元函数从左到右折叠进一个累加值
total = functools.reduce(operator.add, [1, 2, 3, 4, 5])
print('sum fold :', total)
# 无初值时空序列直接抛 TypeError:必须给 initializer 兜底
try:
functools.reduce(operator.add, [])
except TypeError as exc:
print('empty :', exc)
# 有初值时空序列返回初值本身
print('empty init :', functools.reduce(operator.add, [], 0))
# 用 lambda 折叠成结构:逐个把元素追加进累积列表
squares = functools.reduce(lambda acc, n: acc + [n * n], range(1, 6), [])
print('squares :', squares)
# 连乘用 operator.mul:同样的左折叠
print('product :', functools.reduce(operator.mul, [2, 3, 4]))