高阶函数 map,reduce, filter的用法

1. map 用法

 1 def fun_C(x):
 2     """求平方"""
 3     return x ** 2
 4 
 5 
 6 result = map(fun_C, my_list)
 7 print(list(result))
 8 
 9 my_list1 = ["smith", "edward", "john", "obama", "tom"]
10 
11 
12 def f(d):
13     """将列表小写首字母转换为大写字母"""
14     return d[0].upper() + d[1:]
15 
16 
17 result1 = map(f, my_list1)
18 print(list(result1))

2. reduce 用法

对列表中的数字进行累加计算

需要使用 import functools 模块

 1 # reduce模块头文件
 2 import functools
 3 
 4 my_list = [1, 2, 3, 4, 5, 6]
 5 
 6 def sum(a, b):
 7     return a + b
 8 
 9 ret = functools.reduce(sum, my_list)
10 print(ret)

3. filter 用法

filter() 函数用于过滤序列, 过滤掉不符合条件的元素, 返回一个 filter 对象, 如果要转换为列表, 可以使用 list() 来转换.

 1 my_list = [1, 2, 3, 4, 5, 6]
 2 
 3 
 4 def f(x):
 5     """过滤掉奇数"""
 6     return x % 2 == 0
 7 
 8 
 9 result = filter(f, my_list)
10 print(list(result))
11 
12 my_list1 = ["smith", "Edward", "john", "Obama", "tom"]
13 
14 
15 def d(w):
16     """过滤掉列表中首字母为大写的单词"""
17     return w[0].isupper()
18 
19 
20 ret = filter(d, my_list1)
21 print(list(ret))

猜你喜欢

转载自www.cnblogs.com/SP-0306/p/10905951.html