定義
一個函數可以接受另一個函數作為參數,則被稱為高階函數
示例
函數add 接受參數 x,y,f ,調用add時 參數 f 接受的是函數 abs
#一個簡單的高階函數,求兩個參數的絕對值和 def add(x,y,f): return f(x)+f(y) print(add(-5,-6,abs))
內置高階函數-map
map函數接收兩個參數,一個函數,一個 Iterable。 將參數函數作為於 Iterable的每一個元素,然后返回一個新的 Iterable。
示例:以下將求平方的函數傳入map做參數,返回的list為每個值的平方結果
#內置高階函數map的使用 def f(x): return x*x list = [1,2,3,4,5,6,7,8,9,10] list1=map(f,list) print(list(list1))
內置高階函數-reduce
reduce把一個函數作用在一個序列上[x1, x2, x3, ...] ,這個函數必須接受兩個參數,reduce把結果繼續和序列的下一個元素 做 累積計算。
其效果是 rudece(f,[x1,x2,x3,x4]) = f( f( f(x1,x2) x3) x4)
示例
#reduce將序列[1,3,5,7,9]變為 13579 def fn(x,y): return x*10 + y print(reduce(fn,[1,3,5,7,9]))
下面是對http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000 中三個練習題的作業
1.
在下面方法,犯了一個比較窘的錯誤, name.capitalize() ---> 錯誤的寫為了 capitalize(name),報錯 NameError: name 'capitalize' is not defined
#練習:將不規范的名稱修改為首字符大寫,其余小寫的格式
from string import *
L1 = ['adam', 'LISA', 'barT'] def normalize(name): return name.capitalize() name=map(normalize,L1) print(list(name))
2.
#利用reduce函數傳入一個list並求乘積 L2 =[1,3,5,7,9] def prod(x,y): return x * y print(reduce(prod,L2))
3.
#字符串轉為整數,浮點數類型 def str2float(str): #獲得分割后的str1,str2 ===》即 ‘123’,‘456’ str1,str2=str.split('.' , 1) #{'1':1,'2':2}[s]是一個字典取值的寫法。{'a':1,'b':2}是一個字典。[s]是key,類似於索引。 def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] def prod(x,y): return x*10+y # 將char2num作用於拼接后的字符串 numlist=list(map(char2num,str1+str2)) str2num=reduce(prod,numlist) return str2num*math.pow(10,-len(str2))
以上過程中搜索過的知識點:
字符串的分割:https://my.oschina.net/hkmax/blog/146553
字符串拼接:http://python3-cookbook.readthedocs.io/zh_CN/latest/c02/p14_combine_and_concatenate_strings.html
Python字符串操作(string替換、刪除、截取、復制、連接、比較、查找、包含、大小寫轉換、分割等):http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html
math.pow 平方用法:http://www.runoob.com/python/func-number-pow.html