python函數式編程

map

其中,function 參數表示要傳入一個函數,其能夠是內置函數、自定義函數或者 lambda 匿名函數;iterable 表示一個或多個可迭代對象,能夠是列表、字符串等。
map() 函數的功能是對可迭代對象中的每一個元素,都調用指定的函數,並返回一個 map 對象。python

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)code

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)          # 元素個數與最短的列表一致
[(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)]
相關文章
相關標籤/搜索