一学就废|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()返回最后的计算结果。

相关推荐
雷达学弱狗2 小时前
链式法则解释上游梯度应用
开发语言·前端·javascript
爱隐身的官人3 小时前
爬虫基础学习-爬取网页项目(二)
前端·爬虫·python·学习
小清兔5 小时前
c#基础知识
开发语言·数据库·学习·unity·c#·游戏引擎·.net
刘恒1234567895 小时前
Pycharm
ide·python·pycharm
奇某人7 小时前
【语法】【C+V】本身常用图表类型用法快查【CSDN不支持,VSCODE可用】
开发语言·vscode·markdown·mermaid
做一位快乐的码农7 小时前
php程序设计之基于PHP的手工艺品销售网站/基于php在线销售系统/基于php在线购物商城系统
开发语言·php
@珍惜一生@7 小时前
Qt开源库
开发语言·qt·开源
Slaughter信仰8 小时前
深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)第四章知识点问答补充及重新排版
java·开发语言·jvm
心灵宝贝8 小时前
Mac用户安装JDK 22完整流程(Intel版dmg文件安装指南附安装包下载)
java·开发语言·macos
今***b8 小时前
Python 操作 PPT 文件:从新手到高手的实战指南
java·python·powerpoint