一、reduce()函数
1.函数说明
Help on built-in function reduce in module _functools:
reduce(...)
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.
在迭代sequence的过程中,首先先把序列中前两个元素传给function,function加工以后得到结果和第三个元素继续传进function,以此类推。如果有initial,第一次传入function的是 initial和第一个元素。
参数 | 说明 |
---|---|
function | 函数,有两个参数 |
sequence | 可迭代序列 |
initial | 初始参数,可选 |
2.例子
>>> a = [1,2,3,4,5]
>>> def add(x,y):
... return x+y
...
>>> sum = reduce(add,a)
>>> sum
15
二、lambda匿名函数
1.函数说明
如果写程序的过程中有时不需要给函数命名,这个时候匿名函数就可以派上用场了。
匿名函数也是一个函数对象,只能有一个表达式,不用写return
.
2.例子
def add(x,y):
return x+y
lambda x,y: x+y
# 这两个是一样的作用,但是lambda不需要些函数名
>>>sum = add(5,6)
>>>sum
11
>>>sum = lambda x,y:x+y
>>>sum
<function <lambda> at 0x0000026CEE1457B8>
>>>sum(5,6)
>>>11
lambda匿名函数也是可以作为函数的返回值返回的
def add(x,y)
return lambda x,y: x+y