python 函数式编程-匿名函数、高阶函数
1、匿名函数是什么?
def add(x,y): return x+y print(add(1,2)) #普通函数的定义和调用
f = lambda x,y:x+y print(f(1,2)) #匿名函数的定义,并将这个函数赋值给变量,使用变量调用函数 print(f(1,2)) # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test24.py" # 3
以上不能体现匿名函数的方便用法。因为一般lambda表达式是不赋值给变量用的。
对lambda表达式的新理解(202103011):lambda会返回一个函数对象,但这个对象不会赋给一个标识符,而def则会把函数对象赋值给一个变量(函数名)
2、三元表达式
与其他语言不通,python的格式是
为真的结果 if 为真的条件 else 为假的结果
x = 3 y = 2 r = x if x>y else y print(r) # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test25.py" # 3
3、map:使用场景--数学上的映射,内部执行了for循环,挨着盘用function 算了一下
语法:map(function,interator)
list_x = [1,2,3,4,5,6,7] def square(x): return x*x r = map(square,list_x) print(list(r)) # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test26.py" # [1, 4, 9, 16, 25, 36, 49]
总结1~3:map是要结合lambda函数使用的
list_x = [1,2,3,4,5,6,7] r = map(lambda x:x*x, list_x) print(list(r)) # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test26.py" # [1, 4, 9, 16, 25, 36, 49]
简洁一点。
多个入参
list_x = [1,2,3,4,5,6,7] list_y = [1,2,3,4,5,6,7] r = map(lambda x,y:x*x+y, list_x,list_y) print(list(r)) # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test26.py" # [2, 6, 12, 20, 30, 42, 56]
又一个入参比较短,输出长度按照比较短的那个输出
list_x = [1,2,3,4,5,6,7] list_y = [1,2,3,4,5] r = map(lambda x,y:x*x+y, list_x,list_y) print(list(r)) # anson@ansonwandeMacBook-Pro python_ToolCodes % python3 test26.py # [2, 6, 12, 20, 30]
4、reduce
语法 def reduce(function, sequence, initial=None)
#连续计算,连续调用lambdafrom functools import reduce
list_x = [1,2,3,4,5] #list_y = [1,2,3,4,5] r = reduce(lambda x,y: x+y,list_x) print(r) # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test27.py" # 15 # 计算过程 # x=1,y=0 y=1--->第一次调用lambda
# x=2,y=1 y=3--->第二次调用lamda
# x=3,y=3 y=6 # x=4,y=6 y=10 # x=10,y=5 y=15
给个初始值y=10
from functools import reduce list_x = [1,2,3,4,5] #list_y = [1,2,3,4,5] r = reduce(lambda x,y: x+y,list_x,10) print(r) # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test27.py" # 25 # 计算过程 # x=1,y=10 y=11 # x=2,y=11 y=13 # x=3,y=13 y=16 # x=4,y=16 y=20 # x=5,y=20 y=25
5、filter:应用场景,过滤为0数字、过滤大写字母之类的
基础语法:
def filter(function: None, iterable: Iterable[Optional[_T]])
过滤为0的数字 list_x = [1,0,1,0] # def filter_data(x): # return x # for x in list_x: # filter_data(x) r = filter(lambda x:x,list_x) #r = filter(filter_data,list_x) print(list(r)) # [Running] python -u "/Users/anson/Documents/Project/python_ToolCodes/test28.py" # [1, 1]