函数式编程:匿名函数、高阶函数、装饰器
一、lambda表达式
1、非lambda表达式
def add(x, y):
return x + y
print(add(1, 2))
运行结果:
3
2、lambda表达式
f = lambda x, y: x + y
print(f(1, 2))
运行结果:
3
二、三元表达式
x = 2
y = 1
r = x if x > y else y
print(r)
运行结果:
2
x = 2
y = 5
r = x if x > y else y
print(r)
运行结果:
5
三、map
1、非map形式
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
def square(x):
return x * x
list_y = []
for x in list_x:
list_y.append(square(x))
print(list_y)
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64]
2、map形式
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
def square(x):
return x * x
r = map(square, list_x)
print(list(r))
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64]
四、map与lambda
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
list_y = [1, 2, 3, 4, 5, 6]
r = map(lambda x, y: x * x + y, list_x, list_y)
print(list(r))
运行结果:
[2, 6, 12, 20, 30, 42]
注意:传入两个列表的话,运行结果长度等于短列表的的长度。
五、reduce
1、示例一:
# 连续计算,连续调用lambda
# ((((((1 + 2) + 3) + 4) + 5) + 6) + 7) + 8 = 36
list_x = [1, 2, 3, 4, 5, 6, 7, 8]
r = reduce(lambda x, y: x + y, list_x)
print(r)
运行结果:
36
2、示例二:
# 连续计算,连续调用lambda
# ((((((("aaa" + "1") + "2") + "3") + "4") + "5") + "6") + "7") + "8" = "aaa12345678"
list_x = ["1", "2", "3", "4", "5", "6", "7", "8"]
r = reduce(lambda x, y: x + y, list_x, "aaa")
print(r)
运行结果:
aaa12345678
六、filter
1、示例一:
list_x = [1, 0, 1, 0, 0, 1]
r = filter(lambda x: True if x == 1 else False, list_x)
print(list(r))
运行结果:
[1, 1, 1]
2、示例二:
list_x = [1, 0, 1, 0, 0, 1]
r = filter(lambda x: x, list_x)
print(list(r))
运行结果:
[1, 1, 1]
3、示例三:
list_x = ["a", "B", "c", "F", "E"]
r = filter(lambda x: x, list_x)
print(list(r))
运行结果:
['a', 'B', 'c', 'F', 'E']
七、装饰器
from datetime import datetime
def decorator(func):
def wrapper(*args, **kwargs):
print(datetime.now())
func(*args, **kwargs)
return wrapper
@decorator
def f1(func_name):
print("This is a function named " + func_name)
@decorator
def f2(func_name1, func_name2):
print("This is a function named " + func_name1)
print("This is a function named " + func_name2)
@decorator
def f3(func_name1, func_name2, **kwargs):
print("This is a function named " + func_name1)
print("This is a function named " + func_name2)
print(kwargs)
f1("test_func")
运行结果:
2019-10-02 19:37:19.419512
This is a function named test_func
f2("test_func1", "test_func2")
运行结果:
2019-10-02 19:37:19.419532
This is a function named test_func1
This is a function named test_func2
f3("test_func1", "test_func2", a=1, b=2, c="1, 2, 3")
运行结果:
2019-10-02 19:37:19.419544
This is a function named test_func1
This is a function named test_func2
{'a': 1, 'b': 2, 'c': '1, 2, 3'}