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]