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], []], ['@']))  # 这个操作占用空间较大,慎用
相关推荐
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩1 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在2 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP2 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780512 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
c8i2 天前
python中类的基本结构、特殊属性于MRO理解
python
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin05062 天前
【ESP32-CAM】HELLO WORLD
python
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式