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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码路刺客

您的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值