流畅的python-一等函数
在python中函数是一等对象。
一等对象定义
- 在运行时创建
- 能赋值给变量或数据结构中的元素
- 能作为参数传给函数
- 能作为函数的返回结果
一等函数意味着可以使用函数式风格编程
高阶函数
定义:接受函数为参数,或者把函数作为结果返回的函数。例如map函数,sorted函数。
map、filter、reduce、列表推导
map,filter和列表推导的例子
>>> list(map(fact, range(6))) ➊
[1, 1, 2, 6, 24, 120]
>>> [fact(n) for n in range(6)] ➋
[1, 1, 2, 6, 24, 120]
>>> list(map(factorial, filter(lambda n: n % 2, range(6)))) ➌
[1, 6, 120]
>>> [factorial(n) for n in range(6) if n % 2] ➍
[1