您的位置:首页 > 编程语言 > Python开发

Python中reduce与lambda的结合使用

2017-08-11 23:40 567 查看
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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: