python学习系列14——函数应用
(一)lambda表达式(匿名函数)
return 后面的部分使用 lambda 关键字定义的就是 lambda 表达式,Python 要求 lambda 表达式只能是单行表达式。
代码:
1 def get_math_func(type): 2 result = 1 3 # 该函数返回的是Lambda表达式 4 if type == 'square': 5 return lambda n: n * n # ① 6 elif type == 'cube': 7 return lambda n: n * n * n # ② 8 else: 9 return lambda n: (1 + n) * n / 2 # ③ 10 11 # 调用get_math_func(),程序返回一个嵌套函数 12 math_func = get_math_func("cube") 13 print(math_func(5)) 14 math_func = get_math_func("square") 15 print(math_func(5)) 16 math_func = get_math_func("other") 17 print(math_func(5))
结果:
125 25 15.0
(二)eval()和exec()用法
eval() 和 exec() 函数的功能是相似的,都可以执行一个字符串形式的 Python 代码(代码以字符串的形式提供),相当于一个 Python 的解释器。二者不同之处在于,eval() 执行完要返回结果,而 exec() 执行完不返回结果。
代码:
1 a = 1 2 exec("a = 2") #相当于直接执行 a=2 3 print(a) 4 a = exec("2+3") #相当于直接执行 2+3,但是并没有返回值,a 应为 None 5 print(a) 6 a = eval('2+3') #执行 2+3,并把结果返回给 a 7 print(a)
结果:
2
None
5
(三)函数式编程
(1)map()函数
map() 函数的功能是对可迭代对象中的每个元素,都调用指定的函数,并返回一个 map 对象。
代码:
1 listDemo1 = [1, 2, 3, 4, 5] 2 listDemo2 = [3, 4, 5, 6, 7] 3 #map的第一个参数是匿名函数,后面的参数是可迭代对象。 4 new_list = map(lambda x,y: x + y, listDemo1,listDemo2) 5 print(list(new_list))
结果:
[4, 6, 8, 10, 12]
(2)filter()函数
filter() 函数的功能是对 iterable 中的每个元素,都使用 function 函数判断,并返回 True 或者 False,最后将返回 True 的元素组成一个新的可遍历的集合。
代码:
1 listDemo = [1, 2, 3, 4, 5] 2 new_list = filter(lambda x: x % 2 == 0, listDemo) 3 print(list(new_list))
结果:
[2, 4]
(3)reduce()函数
reduce() 函数通常用来对一个集合做一些累积操作。
代码:
1 import functools 2 listDemo = [1, 2, 3, 4, 5] 3 product = functools.reduce(lambda x, y: x * y, listDemo) 4 print(product)
结果:
120

浙公网安备 33010602011771号