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

相关推荐
蓝桉80219 分钟前
图片爬取案例
开发语言·数据库·python
逸狼26 分钟前
【JavaEE进阶】Spring DI
java·开发语言
wang_yb28 分钟前
『Python底层原理』--Python整数为什么可以无限大
python·databook
敲上瘾35 分钟前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
阑梦清川1 小时前
Jupyter里面的manim编程学习
python·jupyter·manim
my_styles1 小时前
2025-alibaba-Sentinel组件
java·开发语言·sentinel
Dongwoo Jeong1 小时前
类型系统下的语言分类与类型系统基础
java·笔记·python·lisp·fortran·type
禁默1 小时前
C++之旅-C++11的深度剖析(1)
开发语言·c++
繁依Fanyi1 小时前
巧妙实现右键菜单功能,提升用户操作体验
开发语言·前端·javascript·vue.js·uni-app·harmonyos
程序员黄同学2 小时前
解释 Vue 中的虚拟 DOM,如何通过 Diff 算法最小化真实 DOM 更新次数?
开发语言·前端·javascript