高阶函数可以接收函数做参数,有些时候,我们不需要显式地定义函数,直接传入匿名函数更方便。
栗子1: 计算 f(x)=x*x 时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:
L1 = map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(L1))
结果为: [1, 4, 9, 16, 25, 36, 49, 64, 81]
可以看出,匿名函数 lambda x: x * x 实际上就是:
def f(x):
return x * x
关键字lambda 表示匿名函数,冒号前面的 x 表示函数参数。
栗子2: 返回函数的时候,也可以返回匿名函数:
myabs = lambda x: -x if x < 0 else x
print(myabs(-1))
结果为: 1
练习: 利用匿名函数简化以下代码
def is_not_empty(s):
return s and len(s.strip()) > 0
L1 = filter(is_not_empty, ['test', None, '', 'str', ' ', 'END'])
print(list(L1))
结果为: [‘test’, ‘str’, ‘END’]
分析: 定义匿名函数时,没有return关键字,且表达式的值就是函数返回值。
故匿名函数为:
L1 = filter(lambda s: s and len(s.strip())>0, ['test', None, '', 'str', ' ', 'END'])
print (list(L1))
结果为: [‘test’, ‘str’, ‘END’]
大家加油!
学习链接: https://www.imooc.com/code/6060