Python函数式编程

一、高阶函数

  满足两个特性任何一个即为高阶函数

    a.函数的传入参数是一个函数名

    b.函数的返回值是一个函数名

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 num_1 = [1, 2, 10, 5, 7]
 4 
 5 
 6 def map_test(func, array):
 7     ret = []
 8     for i in array:
 9         res = func(i)
10         ret.append(res)
11     return ret
12 
13 
14 def add_one(x):
15     return x+1
16 
17 
18 def reduce_one(x):
19     return x-1
20 
21 
22 print(map_test(add_one, num_1))
23 print(map_test(lambda x: x-1, num_1))
24 
25 print('内置函数:', list(map(lambda x: x**2, num_1)))
26 
27 msg = 'chenyanbin'
28 print('匿名函数,小写转大写:', list(map(lambda x: x.upper(), msg)))
map函数
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 movie_people = ['alex', 'sb_zhangsan', 'lisi']
 4 
 5 
 6 def filter_test(func, array):
 7     ret = []
 8     for p in array:
 9         if not func(p):
10             ret.append(p)
11     return ret
12 
13 
14 print(filter_test(lambda x: x.startswith('sb'), movie_people))
filter函数
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # from functools import reduce
 4 # reduce()
 5 num_1 = [1, 2, 3, 4, 5, 6]
 6 
 7 
 8 def reduce_test(func, array, init=None):
 9     if init is None:
10         res = array.pop(0)
11     else:
12         res = init
13     for num in array:
14         res = func(res, num)
15     return res
reduce函数

小结:

map():处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样

filter():遍历序列中的每个元素,判断每个元素返回一个布尔值,如果是True则留下来

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 people = [
4     {'name': 'alex', 'age': 1000},
5     {'name': 'zhangsan', 'age': 10000},
6     {'name': 'wangwu', 'age': 18}
7 ]
8 print(list(filter(lambda p: p['age'] <= 18, people)))
View Code

reduce():处理一个序列,然后把序列进行合并操作

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 from functools import reduce
4 print(reduce(lambda x, y: x + y, range(101)))
View Code

 

posted @ 2019-01-17 21:58  陈彦斌  阅读(229)  评论(0)    收藏  举报