淺析python函數(shù)式編程
目錄
- map
- filter
- reduce
- zip
- sortedmap
map
其中,function 參數(shù)表示要傳入一個函數(shù),其可以是內(nèi)置函數(shù)、自定義函數(shù)或者 lambda 匿名函數(shù);iterable 表示一個或多個可迭代對象,可以是列表、字符串等。
map() 函數(shù)的功能是對可迭代對象中的每個元素,都調(diào)用指定的函數(shù),并返回一個 map 對象。
listDemo = [1, 2, 3, 4, 5] new_list = map(lambda x: x * 2, listDemo) print(list(new_list))
filter
filter() 函數(shù)的功能是對 iterable 中的每個元素,都使用 function 函數(shù)判斷,并返回 True 或者 False,最后將返回 True 的元素組成一個新的可遍歷的集合。
listDemo = [1, 2, 3, 4, 5] new_list = filter(lambda x: x % 2 == 0, listDemo) print(list(new_list))
reduce
reduce() 函數(shù)通常用來對一個集合做一些累積操作,其基本語法格式為:
reduce(function, iterable)
import functools listDemo = [1, 2, 3, 4, 5] product = functools.reduce(lambda x, y: x * y, listDemo) print(product)
zip
>>>a = [1,2,3] >>>b = [4,5,6] >>>c = [4,5,6,7,8] >>>zipped = zip(a,b) # 打包為元組的列表 [(1, 4), (2, 5), (3, 6)] >>>zip(a,c) # 元素個數(shù)與最短的列表一致 [(1, 4), (2, 5), (3, 6)] >>>zip(*zipped) # 與 zip 相反,可理解為解壓,返回二維矩陣式 [(1, 2, 3), (4, 5, 6)]
sorted
>>> L=[('b',2),('a',1),('c',3),('d',4)] >>> sorted(L, key=lambda x:x[1]) # 利用key [('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>> sorted(students, key=lambda s: s[2]) # 按年齡排序 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
以上就是淺析python函數(shù)式編程的詳細(xì)內(nèi)容,更多關(guān)于python函數(shù)式編程的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python中dtypes和type()函數(shù)的區(qū)別示例詳解
type()是python內(nèi)置的函數(shù),type()返回數(shù)據(jù)結(jié)構(gòu)類型(list、dict、numpy.ndarray 等),dtype返回數(shù)據(jù)元素的數(shù)據(jù)類型(int、float等),這篇文章主要給大家介紹了關(guān)于python中dtypes和type()函數(shù)區(qū)別的相關(guān)資料,需要的朋友可以參考下2024-03-03詳解?PyTorch?Lightning模型部署到生產(chǎn)服務(wù)中
這篇文章主要為大家介紹了如何將PyTorch?Lightning模型部署到生產(chǎn)服務(wù)中的詳細(xì)教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09python json.dumps() json.dump()的區(qū)別詳解
這篇文章主要介紹了python json.dumps() json.dump()的區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07