1.高階函式介紹:
- 一個函式可以作為引數傳給另外一個函式,或者一個函式的回傳值為另外一個函式(若回傳值為該函式本身,則為遞回),如果滿足其一,則為高階函式,
- 常見的高階函式:map()、sorted()、filter()等也是python內置的函式,也可以自定義高階函式,其實裝飾器也算一種高階函式,
2.內置高階函式:
(1)map(function,iterable) 函式
- function:接收一個函式
- iterable:接受一個可迭代物件(字串,元組,串列,字典)
- 作用:可將迭代物件 __iter1 依次代入這個函式,然后將結果組成一個串列回傳
""" #將串列 a 中的元素全部轉換成字串 a = [1,2,3,4] b = map(str,a) print(list(b)) """ """ #將下面stu串列中的姓氏進行首字母大寫操作 stu = ["ZHAo","qIan","SUN","Li"] #自定義首字母大寫方法 def NameStyle(name): return name[0].upper() + name[1:].lower() #使用map()函式,傳入引數為,自定義的函式NameStyle名稱,和可迭代物件stu stu2 = map(NameStyle,stu) print(list(stu2)) """
(2)filter(function,iterable) 函式
- function:接收一個函式
- iterable:接受一個可迭代物件
- 作用:將可迭代物件依次傳入該函式,通過回傳值是 True 或 False 決定去留(過濾或篩選)
""" #找出串列 strs 中的所有字串 strs = ["a","b","c",1,2] def get_str(x): if isinstance(x,str): #判斷傳入的元素 x 是否是 str 型 return True new_strs = filter(get_str,strs) print(list(new_strs)) """ """ #找出串列中http鏈接 http = ["http://www.baidu.com","apple","http://weibo.cn","中國人"] def ht(param): if param.startswith("http"): return True all_http = filter(ht,http) print(list(all_http)) """
(3)sorted(iterable,key,reverse) 函式
- iterable:可迭代物件
- key:主要是用來進行比較的元素,只有一個引數,具體的函式的引數就是取自于可迭代物件中,指定可迭代物件中的一個元素來進行排序
- reverse:排序規則,reverse = True 降序 , reverse = False 升序(默認)
- 回傳值:回傳重新排序的串列
""" #根據成績排序 grade = [("Tom",75),("Jerry",92),("Apple",66),("Ben",88)] def get_grade(x): return x[1] print(sorted(grade,key=get_grade)) """ """ # 根據字串長度排序 name = ["Tom","Jerry","Apple","Ben"] def len_name(x): return len(x) print(sorted(name,key=len_name)) """
3.嵌套函式
- 函式內部再進行定義函式成為嵌套函式
def foo(): msg = "China" def fo(): return msg return fo() print(foo())
4.匿名函式
- 特點:
- 只能有一個運算式
- 匿名函式只有一個引數
- 匿名函式也是一個函式物件,可以賦值給一個變數
- 經常配合高階函式使用
#計算出串列中所有值的平方 li = [1,2,3,4,5] """ #高階函式用法 def foo(x): return x * x print(list(map(foo,li))) """ #匿名函式用法 """ print(list(map(lambda x: x * x,li))) #第一個 x 為引數,x * x 為計算邏輯 """
#匿名函式賦值給變數 f f = lambda x: x * x print(f(2))
#求出 1-20 的所有奇數 J = list(filter(lambda x: x % 2 != 0,range(1,20))) print(J)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/188618.html
標籤:Python
