python 函數語言程式設計-匿名函式、高階函式
阿新 • • 發佈:2020-08-10
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表示式是不賦值給變數用的。
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(lambdax,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]