一、lambda函数的语法
lambda语句中,冒号前是参数,可以有0个或多个,用逗号隔开,冒号右边是返回值。lambda语句构建的其实是一个函数对象。
1》无参数:
f = lambda:'Hello python lambda'
f()
#'Hello python lambda'
2》有参数,无默认值
f = lambda x,y: x*y
f(6,7)
#42
3》有参数,有默认值
f = lambda x=5, y=8: x*y
f()
#40
f(5,6)
#30
4》和map, reduce, filter连用
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print filter(lambda x: x % 3 == 0, foo)#python 2.x
list( filter(lambda x: x % 3 == 0, foo) )#python 3.x
#[18, 9, 24, 12, 27]
print map(lambda x: x * 2 + 10, foo)#python 2.x
list( map(lambda x: x * 2 + 10, foo) )#python 3.x
#[14, 46, 28, 54, 44, 58, 26, 34, 64]
from functools import reduce#python 3.x need import reduce
reduce(lambda x, y: x + y, foo)
#139