Lambda函数也叫匿名函数,即,函数没有具体的名称。先看一个例子:
def f(x): return x**2 print f(4)Python中使用lambda的话,写成这样:
g = lambda x : x**2 print g(4)
涵义
Lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒号右边的是返回值。lambda语句构建的是一个函数对象,举例:
g = lambda x : x**2 print g <function <lambda> at 0x00AFAAF0>
Lambda表达式有何用处呢?
lambda和普通函数相比,就是省去了函数名称而已,同时这样的匿名函数,又不能共享在别的地方调用。在使用Python写脚本时,使用lambda可以省去定义函数的过程,让代码更加精简;
对于一些抽象的,不会在别的地方再复用的函数,有时候给函数起个名字也是个难题,使用lambda不需要考虑命名的问题;
使用lambda在某些时候让代码更容易理解。