淺析python函數式編程
目錄
map filter reduce zip sortedmapmap
其中,function 參數表示要傳入一個函數,其可以是內置函數、自定義函數或者 lambda 匿名函數;iterable 表示一個或多個可迭代對象,可以是列表、字符串等。map() 函數的功能是對可迭代對象中的每個元素,都調用指定的函數,并返回一個 map 對象。
listDemo = [1, 2, 3, 4, 5]new_list = map(lambda x: x * 2, listDemo)print(list(new_list))
filter
filter() 函數的功能是對 iterable 中的每個元素,都使用 function 函數判斷,并返回 True 或者 False,最后將返回 True 的元素組成一個新的可遍歷的集合。
listDemo = [1, 2, 3, 4, 5]new_list = filter(lambda x: x % 2 == 0, listDemo)print(list(new_list))
reduce
reduce() 函數通常用來對一個集合做一些累積操作,其基本語法格式為:reduce(function, iterable)
import functoolslistDemo = [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) # 元素個數與最短的列表一致[(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函數式編程的詳細內容,更多關于python函數式編程的資料請關注好吧啦網其它相關文章!
相關文章: