25 Python常用函数——reduce()

在 Python 3.x 中,reduce() 不是内置函数,而是放到了标准库 functools 中,需要先导入再使用。

标准库 functools 中的函数 reduce() 可以将一个接受两个参数的函数以迭代累积的方式从左到右依次作用到一个序列或迭代器对象的所有元素上,并且允许指定一个初始值。

cpp 复制代码
from functools import reduce

# 计算过程为 ((((1+2)+3)+4)+5)
print(reduce(lambda i, j: i + j, [1, 2, 3, 4, 5]))


def get(x, y):
    return x + y


print(reduce(get, list(range(10))))
print(reduce(get, range(10)))  # 可以不用转换为列表
print(reduce(lambda i, j: i + j, range(10)))  # 使用 lambda 表达式实现相同功能

import operator  # 保准库 operator 提供了大量运算

print(operator.add(128, 64))  # 可以像普通函数一样直接调用

print(reduce(operator.add, range(10)))
print(reduce(operator.mul, range(1, 10)))  # 乘法运算
print(reduce(operator.add, range(10), 5))  # 指定累加的初始值为5
print([reduce(operator.add, map(str, range(10)))])  # 转换成字符串再累加
print([''.join(map(str, range(10)))])  # 使用join方法实现字符串连接
print(reduce(operator.add, [[1, 2], [3], []], ['@']))  # 这个操作占用空间较大,慎用
相关推荐
曲幽8 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805113 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon14 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly14 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程15 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly17 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python