函数式编程
2016-06-15 16:26
260 查看
函数式编程
高阶函数
变量可以指向函数
f=abs print f(-10) # 输出:10
函数名也是变量
bs = 10 print abs(-10) """ 报错: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable` """
上述代码说明,函数名也是变量
传入函数
既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。一个最简单的高阶函数:
def add(x, y, f): return f(x) + f(y)
当我们调用add(-5, 6, abs)时,参数x,y和f分别接收-5,6和abs,
add(-5, 6, abs) # 输出:11
编写高阶函数,就是让函数的参数能够接收别的函数。
map/reduce
Python内建了map()和reduce()函数。map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。
举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下:
def f(x): return x * x print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # 输出:[1, 4, 9, 16, 25, 36, 49, 64, 81]
把这个list所有数字转为字符串:
map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]) ['1', '2', '3', '4', '5', '6', '7', '8', '9']
reduce()用法
比方说对一个序列求和,就可以用reduce实现:
def add(x, y): return x + y print reduce(add, [1, 3, 5, 7, 9]) # 输出:25
把str转换为int的函数:
def fn(x,y): return x*10+y def char2num(s): return {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}[s] print reduce(fn, map(char2num, "13579"))
整理成一个str2int的函数就是:
def str2int(s): def fn(x, y): return x * 10 + y def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] return reduce(fn, map(char2num, s))
使用lambda函数进一步简化成:
def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] def str2int(s): return reduce(lambda x,y: x*10+y, map(char2num, s))
练习
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']。def normalize(s): return s[0].upper() + s[1:].lower() print map(normalize, ["aDAD", "AdsE", "SDa"])
Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积。
def prod(a): return reduce(lambda x, y: x * y, a) print prod([1, 2, 3, 4, 5])
filter
Python内建的filter()函数用于过滤序列。和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
def is_odd(n): return n % 2 == 1 print filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # 结果: [1, 5, 9, 15]
去除空字符串
def not_empty(s): return s and s.strip() filter(not_empty, ['A', '', 'B', None, 'C', ' ']) # 结果: ['A', 'B', 'C']
去除素数
def is_prime(n): j = 2 while j < n: if n % j == 0: return False else: j = j + 1 return True print filter(is_prime, range(2, 100))
sorted
Python内置的sorted()函数就可以对list进行排序:sorted([36, 5, 12, 9, 21]) # 输出:[5, 9, 12, 21, 36]
sorted()函数也是一个高阶函数,它还可以接收一个比较函数来实现自定义的排序。比如,如果要倒序排序,我们就可以自定义一个reversed_cmp函数:
def reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 return 0 sorted([36, 5, 12, 9, 21], reversed_cmp) # 输出:[36, 21, 12, 9, 5]
返回函数
函数作为返回值
高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum
闭包
函数返回函数
匿名函数
匿名函数lambda x: x * xdef f(x): return x * x
关键字lambda表示匿名函数,冒号前面的x表示函数参数
匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
装饰器
假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。本质上,decorator就是一个返回函数的高阶函数。所以,我们要定义一个能打印日志的decorator,可以定义如下:
def log(func): def wrapper(*args, **kwargs): print "call %s():" % func.__name__ return func(*args, **kwargs) return wrapper @log def now(): print "2016/6/15" print now() """ call now(): 2016/6/15 """
把@log放到now()函数的定义处,相当于执行了语句
now = log(now)
由于log()是一个decorator,返回一个函数,所以,原来的now()函数仍然存在,只是现在同名的now变量指向了新的函数,于是调用now()将执行新函数,即在log()函数中返回的wrapper()函数。
如果decorator本身需要传入参数,那就需要编写一个返回decorator的高阶函数,写出来会更复杂。比如,要自定义log的文本:
def log(text): def decorator(func): def wrapper(*args, **kw): print '%s %s():' % (text, func.__name__) return func(*args, **kw) return wrapper return decorator @log('execute') def now(): print '2016-6-15' print now() # 输出:execute now(): # 2016-6-15
3层嵌套的效果是这样的
now = log('execute')(now)
偏函数
Python的functools模块提供了很多有用的功能,其中一个就是偏函数(Partial function)。要注意,这里的偏函数和数学意义上的偏函数不一样。通过设定参数的默认值,可以降低函数调用的难度。而偏函数也可以做到这一点
import functools int2 = functools.partial(int, base=2) int2('1000000') # 输出:64 int2('1010101') # 输出:85
上述偏函数相当于
def int2(x, base=2): return int(x, base) int2('1000000') # 输出:64
相关文章推荐
- python 高阶函数
- python 高阶函数(二)
- @periodic_task简述及nova资源刷新机制
- Python装饰器(Decorate)使用图解
- Python基础4 装饰器
- python 装饰器
- Python 中的装饰器
- python装饰器学习笔记
- Python 进阶----*args和 **kwargs,装饰器 的用法
- Python 函数注释
- Python 闭包
- Python 嵌套函数
- Python 函数的高级用法
- Python 匿名(lambda)函数
- python第17天:函数补充(zip,map,reduce,filter等)
- python装饰器
- start—py(2、高阶函数)
- Python装饰器学习
- Python 装饰器
- 【QTP】等待页面加载的几种方法