map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
def format_name(s): return s[0].upper() + s[1:].lower() print map(format_name, ['adam', 'LISA', 'barT']) 3.python中reduce()函数reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。
def f(x, y): return x + y print reduce(f, [1, 3, 5, 7, 9]) # 25 def prod(x, y): return x * y print reduce(prod, [2, 4, 5, 7, 12]) # 3360 4.python中filter()函数filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
def is_odd(x): return x % 2 == 1 print filter(is_odd, [1, 4, 6, 7, 9, 12, 17]) # [1, 7, 9, 17] def is_not_empty(s): return s and len(s.strip()) > 0 print filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']) # ['test', 'str', 'END'] import math def is_sqr(x): r = int(math.sqrt(x)) return r*r==x print filter(is_sqr, range(1, 101)) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 5.python中自定义排序函数sorted()是一个高阶函数,它可以接收一个比较函数来实现自定义排序,比较函数的定义是,传入两个待比较的元素 x, y,如果 x 应该排在 y 的前面,返回 -1,如果 x 应该排在 y 的后面,返回 1。如果 x 和 y 相等,返回 0。
print sorted([36, 5, 12, 9, 21]) # [5, 9, 12, 21, 36] def reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 return 0 print sorted([36, 5, 12, 9, 21], reversed_cmp) # [36, 21, 12, 9, 5] print sorted(['bob', 'about', 'Zoo', 'Credit']) # ['Credit', 'Zoo', 'about', 'bob'] def cmp_ignore_case(s1, s2): u1 = s1.upper() u2 = s2.upper() if u1 < u2: return -1 if u1 > u2: return 1 return 0 print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case) # ['about', 'bob', 'Credit', 'Zoo'] 6.python中返回函数Python的函数不但可以返回int、str、list、dict等数据类型,还可以返回函数!
def calc_sum(lst): def lazy_sum(): return sum(lst) return lazy_sum print f # <function lazy_sum at 0x1037bfaa0> print f() # 10 def calc_prod(lst): def lazy_prod(): def f(x, y): return x * y return reduce(f, lst, 1) return lazy_prod f = calc_prod([1, 2, 3, 4]) print f() # 24 7.python中闭包 def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fs f1, f2, f3= count() print f1() # 9 print f2() # 9 print f3() # 9 def count(): fs = [] for i in range(1, 4): def f(j): def g(): return j*j return g r = f(i) fs.append(r) return fs f1, f2, f3 = count() print f1(), f2(), f3() # 1 4 9 8.python中匿名函数高阶函数可以接收函数做参数,有些时候,我们不需要显式地定义函数,直接传入匿名函数更方便。
print map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # [1, 4, 9, 16, 25, 36, 49, 64, 81] print sorted([1, 3, 9, 5, 0], lambda x,y: -cmp(x,y)) # [9, 5, 3, 1, 0] myabs = lambda x: -x if x < 0 else x print myabs(-1) # 1 print myabs(1) # 1 print filter(lambda s: s and len(s.strip())>0, ['test', None, '', 'str', ' ', 'END']) # ['test', 'str', 'END'] 9. python中decorator装饰器什么是装饰器?
问题: 定义一个函数 想在运行时动态增加功能 又不想改动函数本身的代码装饰器的作用
可以极大地简化代码,避免每个函数编写重复性代码 打印日志:@log 检测性能:@performance 数据库事务:@transaction URL路由:@post('/register') 9-1. python中编写无参数decoratorPython的 decorator 本质上就是一个高阶函数,它接收一个函数作为参数,然后,返回一个新函数。
def log(f): def fn(x): print 'call ' + f.__name__ + '()...' # call factorial()... return f(x) return fn @log def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial(10) # 3628800 print '\n' import time def performance(f): def fn(*args, **kw): t1 = time.time() r = f(*args, **kw) t2 = time.time() print 'call %s() in %fs' % (f.__name__, (t2 - t1)) # call factorial() in 0.001343s return r return fn @performance def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial(10) # 3628800 9-2. python中编写带参数decorator import time def performance(unit): def perf_decorator(f): def wrapper(*args, **kw): t1 = time.time() r = f(*args, **kw) t2 = time.time() t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1) print 'call %s() in %f %s' % (f.__name__, t, unit) # call factorial() in 1.250982 ms return r return wrapper return perf_decorator @performance('ms') def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial(10) # 3628800 9-3. python中完善decorator@decorator可以动态实现函数功能的增加,但是,经过
@decorator“改造”后的函数,和原函数相比,除了功能多一点外,有没有其它不同的地方?
def f1(x): pass print f1.__name__ # f1 def log(f): def wrapper(*args, **kw): print 'call...' return f(*args, **kw) return wrapper @log def f2(x): pass print f2.__name__ # wrapper import time, functools def performance(unit): def perf_decorator(f): @functools.wraps(f) def wrapper(*args, **kw): t1 = time.time() r = f(*args, **kw) t2 = time.time() t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1) print 'call %s() in %f %s' % (f.__name__, t, unit) return r return wrapper return perf_decorator @performance('ms') def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial.__name__ # factorial 10. python中偏函数当一个函数有很多参数时,调用者就需要提供多个参数。如果减少参数个数,就可以简化调用者的负担。
import functools sorted_ignore_case = functools.partial(sorted, cmp=lambda s1, s2: cmp(s1.upper(), s2.upper())) print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit']) # ['about', 'bob', 'Credit', 'Zoo']