Python函数式编程(进阶2)

1. python把函数作为参数

1 import math
2 def add(x, y, f):
3     return f(x) + f(y)
4     
5 print add(-5, 9, abs)
6 print abs(-5) + abs(9)
7 print add(25, 9, math.sqrt)

 

2. python中map()函数

  map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

1 def format_name(s):
2     return s[0].upper() + s[1:].lower()
3     
4 print map(format_name, ['adam', 'LISA', 'barT'])

 

3.python中reduce()函数

  reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个

  参数,reduce()对list的每 个元素反复调用函数f,并返回最终结果值。

1 def f(x, y):
2     return x + y
3     print reduce(f, [1, 3, 5, 7, 9])  # 25
4 
5 def prod(x, y):
6     return x * y
7 print reduce(prod, [2, 4, 5, 7, 12]) # 3360

 

4.python中filter()函数

  filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,

  filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

 1 def is_odd(x):
 2     return x % 2 == 1
 3 print filter(is_odd, [1, 4, 6, 7, 9, 12, 17]) # [1, 7, 9, 17]
 4 
 5 def is_not_empty(s):
 6     return s and len(s.strip()) > 0
 7 print filter(is_not_empty, ['test', None, '', 'str', '  ', 'END']) # ['test', 'str', 'END']
 8 
 9 import math
10 def is_sqr(x):
11     r = int(math.sqrt(x))
12     return r*r==x
13 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。

 1 print sorted([36, 5, 12, 9, 21]) # [5, 9, 12, 21, 36]
 2 
 3 
 4 def reversed_cmp(x, y):
 5     if x > y:
 6         return -1
 7     if x < y:
 8         return 1
 9     return 0
10 print sorted([36, 5, 12, 9, 21], reversed_cmp) # [36, 21, 12, 9, 5]
11 
12 print sorted(['bob', 'about', 'Zoo', 'Credit']) # ['Credit', 'Zoo', 'about', 'bob']
13 
14 def cmp_ignore_case(s1, s2):
15     u1 = s1.upper()
16     u2 = s2.upper()
17     if u1 < u2:
18         return -1
19     if u1 > u2:
20         return 1
21     return 0
22 print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case) # ['about', 'bob', 'Credit', 'Zoo']

 

6.python中返回函数

  Python的函数不但可以返回int、str、list、dict等数据类型,还可以返回函数!

 1 def calc_sum(lst):
 2     def lazy_sum():
 3         return sum(lst)
 4     return lazy_sum
 5     
 6 print f # <function lazy_sum at 0x1037bfaa0>
 7 print f() # 10
 8 
 9 def calc_prod(lst):
10     def lazy_prod():
11         def f(x, y):
12             return x * y
13         return reduce(f, lst, 1)
14     return lazy_prod
15 f = calc_prod([1, 2, 3, 4])
16 print f() # 24

 

7.python中闭包

 1 def count():
 2     fs = []
 3     for i in range(1, 4):
 4         def f():
 5              return i*i
 6         fs.append(f)
 7     return fs
 8 
 9 f1, f2, f3= count()
10 print f1() # 9
11 print f2() # 9
12 print f3() # 9
13 
14 def count():
15     fs = []
16     for i in range(1, 4):
17         def f(j):
18             def g():
19                 return j*j
20             return g
21         r = f(i)
22         fs.append(r)
23     return fs
24 f1, f2, f3 = count()
25 print f1(), f2(), f3() # 1 4 9

 

8.python中匿名函数

  高阶函数可以接收函数做参数,有些时候,我们不需要显式地定义函数,直接传入匿名函数更方便。

1 print map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # [1, 4, 9, 16, 25, 36, 49, 64, 81]
2 
3 print sorted([1, 3, 9, 5, 0], lambda x,y: -cmp(x,y)) # [9, 5, 3, 1, 0]
4 
5 myabs = lambda x: -x if x < 0 else x 
6 print myabs(-1) # 1
7 print myabs(1) # 1
8 
9 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中编写无参数decorator

  Python的 decorator 本质上就是一个高阶函数,它接收一个函数作为参数,然后,返回一个新函数。

 1 def log(f):
 2     def fn(x):
 3         print 'call ' + f.__name__ + '()...' # call factorial()...
 4         return f(x)
 5     return fn
 6 
 7 @log
 8 def factorial(n):
 9     return reduce(lambda x,y: x*y, range(1, n+1))
10 print factorial(10) # 3628800
11 
12 print '\n'
13 
14 import time
15 def performance(f):
16     def fn(*args, **kw):
17         t1 = time.time()
18         r = f(*args, **kw)
19         t2 = time.time()
20         print 'call %s() in %fs' % (f.__name__, (t2 - t1)) # call factorial() in 0.001343s
21         return r
22     return fn
23 
24 @performance
25 def factorial(n):
26     return reduce(lambda x,y: x*y, range(1, n+1))
27 print factorial(10) # 3628800

 

9-2. python中编写带参数decorator

 1 import time
 2 def performance(unit):
 3     def perf_decorator(f):
 4         def wrapper(*args, **kw):
 5             t1 = time.time()
 6             r = f(*args, **kw)
 7             t2 = time.time()
 8             t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1)
 9             print 'call %s() in %f %s' % (f.__name__, t, unit) # call factorial() in 1.250982 ms
10             return r
11         return wrapper
12     return perf_decorator
13 
14 @performance('ms')
15 def factorial(n):
16     return reduce(lambda x,y: x*y, range(1, n+1))
17 print factorial(10) # 3628800

 

9-3. python中完善decorator

  @decorator可以动态实现函数功能的增加,但是,经过 @decorator“改造”后的函数,和原函数相比,除了功能多一点外,有没有其它不同的地方?

 1 def f1(x):
 2     pass
 3 print f1.__name__ # f1
 4 
 5 def log(f):
 6     def wrapper(*args, **kw):
 7         print 'call...'
 8         return f(*args, **kw)
 9     return wrapper
10 @log
11 def f2(x):
12     pass
13 print f2.__name__ # wrapper
14 
15 import time, functools
16 def performance(unit):
17     def perf_decorator(f):
18         @functools.wraps(f)
19         def wrapper(*args, **kw):
20             t1 = time.time()
21             r = f(*args, **kw)
22             t2 = time.time()
23             t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1)
24             print 'call %s() in %f %s' % (f.__name__, t, unit)
25             return r
26         return wrapper
27     return perf_decorator
28 
29 @performance('ms')
30 def factorial(n):
31     return reduce(lambda x,y: x*y, range(1, n+1))
32 print factorial.__name__ # factorial

 

10. python中偏函数

  当一个函数有很多参数时,调用者就需要提供多个参数。如果减少参数个数,就可以简化调用者的负担。

1 import functools
2 sorted_ignore_case = functools.partial(sorted, cmp=lambda s1, s2: cmp(s1.upper(), s2.upper()))
3 print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit']) # ['about', 'bob', 'Credit', 'Zoo']


 

posted on 2017-02-21 10:45  我的MrFiona博客  阅读(415)  评论(0编辑  收藏  举报

导航