网站首页 > 基础教程 正文
reduce(fun,seq)函数用于将在其参数中传递的特定函数应用于传递的序列中提到的所有列表元素。使用该函数,需要引入functools模块。
让我们从一个简单的例子开始,将一个列表中的所有数字相加。
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()成为一个简洁而强大的工具,用于聚合任务,如求和、乘法或查找最大值。
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 函数类似的功能,并使代码更具可读性。
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()不同。
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()返回最后的计算结果。
猜你喜欢
- 2024-12-31 Python中8种Functools使用方法
- 2024-12-31 有效提升Python代码性能的三个层面
- 2024-12-31 Pytorch - 手写Allreduce分布式训练
- 2024-12-31 Python魔法函数(特殊函数)
- 2024-12-31 解开 Python 单行代码的魔力:高效编写代码的基本函数
- 2024-12-31 浅谈Python中骚操作
- 2024-12-31 Python:使用快速简单的 Lambda 表达式改变您的编程风格
- 2024-12-31 Python零基础入门—15个最受欢迎的Python开源框架
- 2024-12-31 用好这几个Python高阶函数!效率翻倍
- 2024-12-31 Python中级篇~函数式编程的概念和原则(匿名函数和高阶函数)
- 05-24php实现三方支付的方法有哪些?
- 05-24CosmicSting 漏洞影响 75% 的 Adobe Commerce 和 Magento 网站
- 05-24Java接口默认方法的奇妙用途
- 05-24抽象类和接口
- 05-24详解Java抽象类和接口
- 05-24拒绝接口裸奔!开放API接口签名验证
- 05-24每天学Java!Java中的接口有什么作用
- 05-24Java:在Java中使用私有接口方法
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- deletesql (62)
- c++模板 (62)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)