一学就废|Python基础碎片,reduce函数

reduce(fun,seq )函数用于将在其参数中传递的特定函数应用于传递的序列中提到的所有列表元素。使用该函数,需要引入functools模块。

让我们从一个简单的例子开始,将一个列表中的所有数字相加。

python 复制代码
from functools import reduce

# Function to add two numbers
def add(x, y):
    return x + y

a = [1, 2, 3, 4, 5]
res = reduce(add, a)

print(res)  

输出结果 15

reduce()函数将 add() 函数累积应用于列表中的每个数字。首先,1+2=3,然后3+3=6,依此类推,直到处理完所有数字,最终结果为 15。

reduce函数语法

functools.reduce(function, iterable[, initializer])

function:接受两个参数并对其执行操作的函数。

iterable:其元素由函数处理的可迭代对象。

initializer(可选):操作的起始值。如果提供,它被放在可迭代对象中的第一个元素之前。

配合lambda函数使用

当与 lambda 函数配合使用时,reduce()成为一个简洁而强大的工具,用于聚合任务,如求和、乘法或查找最大值。

python 复制代码
from functools import reduce

# Summing numbers with reduce and lambda
a = [1, 2, 3, 4, 5]
res = reduce(lambda x, y: x + y, a)

print(res)

15

lambda 函数接受两个参数(x 和 y)并返回它们的总和。reduce()首先将函数应用于前两个元素: 1+2=3。然后将结果3与下一个元素相加:3+3=6,依此类推。该过程一直持续到所有元素都被加和,产生 15。

reduce()与运算符函数一起使用

reduce()也可以与运算符函数结合使用,以实现与 lambda 函数类似的功能,并使代码更具可读性。

python 复制代码
import functools
import operator

# initializing list
a = [1, 3, 5, 6, 2]

# using reduce with add to compute sum of list
print(functools.reduce(operator.add, a))

# using reduce with mul to compute product
print(functools.reduce(operator.mul, a))

# using reduce with add to concatenate string
print(functools.reduce(operator.add, ["nice", "to", "meet"]))

17
180
nicetomeet

operator. add 和 operator.mul 函数是预定义的运算符。reduce()将函数累积应用于列表中的所有元素。操作与 lambda 示例类似,但代码更清晰易读。

reduce() 与 accumulate() 区别

itertools 模块中的accumulate() 函数也执行累积操作,但它返回一个包含中间结果的迭代器,这与返回单个最终值的reduce()不同。

python 复制代码
from itertools import accumulate
from operator import add

# Cumulative sum with accumulate
a = [1, 2, 3, 4, 5]
res = accumulate(a, add)

print(list(res))

[1, 3, 6, 10, 15]

accumulate() 可看作是reduce()在相同运算下的中间过程列表结果集,reduce()返回最后的计算结果。

相关推荐
蓝婷儿5 分钟前
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
开发语言·python·学习
渣渣盟21 分钟前
基于Scala实现Flink的三种基本时间窗口操作
开发语言·flink·scala
chao_78931 分钟前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
糯米导航43 分钟前
Java毕业设计:办公自动化系统的设计与实现
java·开发语言·课程设计
糯米导航1 小时前
Java毕业设计:WML信息查询与后端信息发布系统开发
java·开发语言·课程设计
MessiGo1 小时前
Javascript 编程基础(5)面向对象 | 5.1、构造函数实例化对象
开发语言·javascript·原型模式
大霞上仙1 小时前
nonlocal 与global关键字
开发语言·python
galaxy_strive1 小时前
绘制饼图详细过程
开发语言·c++·qt
Mark_Aussie2 小时前
Flask-SQLAlchemy使用小结
python·flask
程序员阿龙2 小时前
【精选】计算机毕业设计Python Flask海口天气数据分析可视化系统 气象数据采集处理 天气趋势图表展示 数据可视化平台源码+论文+PPT+讲解
python·flask·课程设计·数据可视化系统·天气数据分析·海口气象数据·pandas 数据处理