定义
Lambda函数又称匿名函数,常用用替换简单函数,使代码逻辑更加紧凑
简单讲 ‘:’前面的为传递参数,后面的为实际方法
例子
1.将一个列表中的所有数值增加2
传统写法


def add(x):View Code
return x+2
print map(add,[y for y in range(5)])
lambda写法


print map(lambda x:x+2,[y for y in range(5)])View Code
2.传递多个函数的lambda


print map(lambda x,y:x+y,[y for y in range(5)],[x for x in range(5,10)])View Code
#返回值[5, 7, 9, 11, 13]
3.带默认值的lambda


print map(lambda x,y=3:x+y,[y for y in range(5)])View Code
#返回[3, 4, 5, 6, 7]
4.官方文档中的例子


def make_incrementor(n):View Code
return lambda x: x + n
f = make_incrementor(42)
f(0) #返回42
f(1) #返回43