Python常見內置高階函數(shù)即高階函數(shù)用法
1.什么是高階函數(shù)?
高階函數(shù):一個函數(shù)可以作為參數(shù)傳給另外一個函數(shù),或者一個函數(shù)的返回值為另外一個函數(shù)(若返回值為該函數(shù)本身,則為遞歸),滿足其一則為高階函數(shù)。
參數(shù)為函數(shù):
#參數(shù)為函數(shù) def bar(): print("in the bar..") def foo(func): func() print("in the foo..") foo(bar)
返回值為函數(shù):
#返回值為函數(shù) def bar(): print("in the bar..") def foo(func): print("in the foo..") return bar res=foo(bar) res()
以上兩個示例中,函數(shù)foo()
為高階函數(shù),示例一中函數(shù)bar作為foo的參數(shù)傳入,示例二中函數(shù)bar作為foo的返回值。
注:函數(shù)名(例如bar 、foo)-->其為該函數(shù)的內存地址;函數(shù)名+括號(例如 bar()、foo() )-->調用該函數(shù)。
2.高階函數(shù)-map、filter、reduce
這三個函數(shù)均為高階函數(shù),其也為Python內置的函數(shù)。接下來我們看一下這三個函數(shù)的用法以及其內部原理是怎樣的:
2.1map函數(shù)
map函數(shù)接收的是兩個參數(shù),一個函數(shù),一個序列,其功能是將序列中的值處理再依次返回至列表內。其返回值為一個迭代器對象--》例如: <map object at 0x00000214EEF40BA8>
。
其用法如圖:
?
接下來我們看一下map函數(shù)的機制是怎么樣的:
num=[1,2,3,4,5] def square(x): return x**2 #map函數(shù)模擬 def map_test(func,iter): num_1=[] for i in iter: ret=func(i) # print(ret) num_1.append(ret) return num_1.__iter__() #將列表轉為迭代器對象 #map_test函數(shù) print(list(map_test(square,num))) #map函數(shù) print(list(map(square,num))) #當然map函數(shù)的參數(shù)1也可以是匿名函數(shù)、參數(shù)2也可以是字符串 print(list(map_test(lambda x:x.upper(),"amanda"))) print(list(map(lambda x:x.upper(),"amanda")))
2.2filter函數(shù)
filter函數(shù)也是接收一個函數(shù)和一個序列的高階函數(shù),其主要功能是過濾。其返回值也是迭代器對象,例如: <filter object at 0x000002042D25EA90>,
其圖示如下:
接下來我們看一下filter函數(shù)的用法以及其機制是怎么樣的:
names=["Alex","amanda","xiaowu"] #filter函數(shù)機制 def filter_test(func,iter): names_1=[] for i in iter: if func(i): #傳入的func函數(shù)其結果必須為bool值,才有意義 names_1.append(i) return names_1 #filter_test函數(shù) print(filter_test(lambda x:x.islower(),names)) #filter函數(shù) print(list(filter(lambda x:x.islower(),names)))
2.3reduce函數(shù)
reduce
函數(shù)也是一個參數(shù)為函數(shù),一個為可迭代對象的高階函數(shù),其返回值為一個值而不是迭代器對象,故其常用與疊加、疊乘等,
圖示例如下:
實例如下:
#reduce函數(shù)不是內置函數(shù),而是在模塊functools中的函數(shù),故需要導入 from functools import reduce nums=[1,2,3,4,5,6] #reduce函數(shù)的機制 def reduce_test(func,array,ini=None): #ini作為基數(shù) if ini == None: ret =array.pop(0) else: ret=ini for i in array: ret=func(ret,i) return ret #reduce_test函數(shù),疊乘 print(reduce_test(lambda x,y:x*y,nums,100)) #reduce函數(shù),疊乘 print(reduce(lambda x,y:x*y,nums,100))
到此這篇關于Python常見內置高階函數(shù)即敢接函數(shù)用法的文章就介紹到這了,更多相關Python高階函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
15個應該掌握的Jupyter Notebook使用技巧(小結)
這篇文章主要介紹了15個應該掌握的Jupyter Notebook使用技巧(小結),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09Python matplotlib 繪制雙Y軸曲線圖的示例代碼
Matplotlib是非常強大的python畫圖工具,這篇文章主要介紹了Python matplotlib 繪制雙Y軸曲線圖,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06詳解修改Anaconda中的Jupyter Notebook默認工作路徑的三種方式
這篇文章主要介紹了詳解修改Anaconda中的Jupyter Notebook默認工作路徑的三種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01