十二、函数式编程:匿名函数、高阶函数、装饰器

一、匿名函数

即没有函数名的函数,又称lambda表达式。

使用关键字lambda

定义:lambda parameter_list:expression 其中parameter_list是参数列表,expression是简单表达式,不能是复杂的代码块。(x+y是表达式;a=x+y不是表达式是代码语句)

特点:1)无函数名;2)无return关键字

学习方法:对比普通函数

例:

 1 #coding=utf-8
 2 
 3 def add(x,y):
 4     #普通函数
 5     return x+y
 6 
 7 f=lambda x,y:x+y#lambda表达式
 8 
 9 print(add(1,2))
10 print(f(1,2))

二、三元表达式

即表达式版本的if...else

例如:比较x和y,x大于y时取x,否则取y.

其他语言的三元表达式:

x>y?x:y

python语言的三元表达式:

伪代码如下

条件为真时返回的结果 if 条件判断 else 条件为假时的结果

x if x>y else y

1 #coding=utf-8
2 
3 x=2
4 y=3
5 r=x if x>y else y
6 print(r)

lambda 后面非常适合三元表达式

三、map

推荐在python代码中多多使用

map是一个类,定义 map(func, *iterables),其中func是方法名,*iterables是一个或多个列表(集合)

适用场景:映射,如抛物线

例如已知列表list_x=[1,2,3,4,5,6,7,8],求list_x中各元素的平方

1、常规实现方法:

 1 # coding=utf-8
 2 
 3 def square(x):
 4     return x * x
 5 
 6 
 7 list_x = [1, 2, 3, 4, 5, 6, 7, 8]
 8 list_y = []
 9 for x in list_x:
10     r = square(x)
11     list_y.append(r)
12 print(list_y)

2、使用map类

1)基础使用

1 # coding=utf-8
2 
3 list_x = [1, 2, 3, 4, 5, 6, 7, 8]
4 r = map(lambda x: x * x, list_x)
5 # print(r)
6 print(list(r))

2)如果lambda有多个参数呢?例如求x*x+y

1 # coding=utf-8
2 
3 list_x = [1, 2, 3, 4, 5, 6, 7, 8]
4 list_y = [1, 2, 3, 4, 5, 6, 7, 8]
5 
6 r = map(lambda x, y: x * x + y, list_x, list_y)
7 
8 print(list(r))

map(func, *iterables)中的*iterables是可变参数,支持多个列表

注意,参数顺序要正确,例如下面的代码,打印结果不同

 1 # coding=utf-8
 2 
 3 list_x = [1, 2, 3, 4, 5, 6, 7, 8]
 4 list_y = [1, 1, 1, 1, 1, 1, 1, 1]
 5 
 6 r1 = map(lambda x, y: x * x + y, list_y, list_x)
 7 r2 = map(lambda x, y: x * x + y, list_x, list_y)
 8 
 9 print(list(r1))
10 print(list(r2))

打印结果

[2, 3, 4, 5, 6, 7, 8, 9]
[2, 5, 10, 17, 26, 37, 50, 65]
3)特殊情况,如果两个列表长度不一致,结果如何?

1 # coding=utf-8
2 
3 list_x = [1, 2, 3, 4, 5, 6, 7, 8]
4 list_y = [1, 1, 1, 1]
5 
6 r = map(lambda x, y: x * x + y, list_x, list_y)
7 
8 print(list(r))

打印结果

[2, 5, 10, 17]

两个列表元素个数要一致,如果不一致,结果取小的。

六、reduce

猜你喜欢

转载自www.cnblogs.com/loveapple/p/9364339.html