Python中reduce与lambda的结合使用

本文探讨了Python内置方法reduce的使用,特别是在结合lambda表达式时如何进行高效操作。通过不同场景的分析,包括function为lambda表达式以及处理函数列表的情况,展示了reduce在处理序列数据时的强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

reduce是Python的内置方法,其官方解释是:

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

function不能为None

考虑没有initial,且function为lambda表达式的情形。此时,lambda表达式的:左边有且须有2个参数,:右边是关于这2个参数的表达式。

reduce(lambda x,y:x+y, [1,2,3]) #6

reduce(lambda x,y:x * y, [1,2,4]) #8

reduce(lambda x,y: x and y, [True,False,True]) #False

def f(x,y):
    return x+y
reduce(lambda x,y:f(x,y), [1,2,3]) #6

考虑没有initial,且function不为lambda表达式的情形。

def f(x,y):
    return x+y
reduce(f, [1,2,3]) #6

考虑有initial,且function为lambda表达式的情形。同样,lambda表达式的:左边有且须有2个参数,:右边是关于这2个参数的表达式。

reduce(lambda x,y:x+y, [1,2,3], 10) #16

reduce(lambda x,y:x+y, [], 10) #10

另外,考虑一种特殊情况,即sequence为函数列表(即列表中的每个元素均是某一个函数)的情况。

def f1(x):
    return x + [1]
def f2(x):
    return x + [2]
reduce(lambda x, y: y(x), [f1, f2], [0]) #[0, 1, 2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值