匿名函数lambda
定义匿名函数
lambda
def fun(x,y):
return x*y
r=lambda x,y: x*y
r(3,4)In [2]: r = lambda x, y: x *y
In [3]: r(3,4)
Out[3]: 12
lambda基础
lambda语句中,冒号前是参数,可以有多个,逗号隔开,冒号右边是返回值
lambda语句构建的其实是一个函数的对象
lambda匿名函数的优点:
1、使用python写一写脚本的时候,使用lambda可以省去定义函数的过程,让代码更加精简
2、对于一些抽象的,不会别别的地方再重复使用的函数,有时候函数起个名字也是难题,使用lambda不需要考虑命名的问题
3、使用lambda在某些时候让代码更容易理解
reduce的用法:
就是通过function()函数去处理sequence序列,reduce内部的function()必须是二元的计算,二元加减乘除
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates处理过程: ((((1+2)+3)+4)+5)
help(reduce)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.
(END)
In [8]: def add(x,y):
...: return x+y
...:
In [9]: reduce(add,range(1,101)) # 1+2+3+4+5+......100=5050
Out[9]: 5050
In [10]: reduce(lambda x,y:x+y,range(1,101))# 1+2+3+4+5+......100=5050
Out[10]: 5050
In [11]: reduce(lambda x,y:x*y,range(1,6)) # 5*4*3*2*1
Out[11]: 120