前言
Python針對眾多的類型,提供了眾多的內建函數來處理,這些內建函數功用在于其往往可對多種類型對象進行類似的操作,即多種類型對象的共有的操作,下面話不多說了,來一看看詳細的介紹吧。
map()
map()函數接受兩個參數,一個是函數,一個是可迭代對象(Iterable),map將傳入的函數依次作用到可迭代對象的每一個元素,并把結果作為迭代器(Iterator)返回。
舉例說明,有一個函數f(x)=x^2 ,要把這個函數作用到一個list[1,2,3,4,5,6,7,8,9]上:
運用簡單的循環可以實現:
>>> def f(x):... return x * x...L = []for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: L.append(f(n))print(L)
運用高階函數map() :
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])>>> list(r)[1, 4, 9, 16, 25, 36, 49, 64, 81]
結果r是一個迭代器,迭代器是惰性序列,通過list()函數讓它把整個序列都計算出來并返回一個list。
如果要把這個list所有數字轉為字符串利用map()就簡單了:
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))['1', '2', '3', '4', '5', '6', '7', '8', '9']
小練習:利用map()函數,把用戶輸入的不規范的英文名字變為首字母大寫其他小寫的規范名字。輸入['adam', 'LISA', 'barT'],輸出['Adam', 'Lisa', 'Bart']
def normalize(name): return name.capitalize() l1=["adam","LISA","barT"] l2=list(map(normalize,l1)) print(l2)
reduce()
reduce()函數也是接受兩個參數,一個是函數,一個是可迭代對象,reduce將傳入的函數作用到可迭代對象的每個元素的結果做累計計算。然后將最終結果返回。
效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
舉例說明,將序列[1,2,3,4,5]變換成整數12345:
>>> from functools import reduce>>> def fn(x, y):... return x * 10 + y...>>> reduce(fn, [1, 2, 3, 4, 5])12345
小練習:編寫一個prod()函數,可以接受一個list并利用reduce求積:
from functools import reducedef pro (x,y): return x * y def prod(L): return reduce(pro,L) print(prod([1,3,5,7]))
map()和reduce()綜合練習:編寫str2float函數,把字符串'123.456'轉換成浮點型123.456
CHAR_TO_FLOAT = { '0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9, '.': -1}def str2float(s): nums = map(lambda ch:CHAR_TO_FLOAT[ch],s) point = 0 def to_float(f,n): nonlocal point if n==-1: point =1 return f if point ==0: return f*10+n else: point =point *10 return f + n/point return reduce(to_float,nums,0)#第三個參數0是初始值,對應to_float中f
新聞熱點
疑難解答