Map,Filter 和 Reduce 三個函數能爲函數式編程提供便利。我們會通過實例⼀個⼀個討論並理解它們。
1、lambda表達式
lambda表達式是⼀⾏函數。
它們在其他語⾔中也被稱爲匿名函數。如果你不想在程序中對⼀個函數使⽤兩次,你也許會想⽤lambda表達式,它們和普通的函數完全⼀樣。
原型:
lambda 參數:操作(參數)
例⼦:
add = lambda x, y: x + y
print(add(4, 6))
# Output: 10
這還有⼀些lambda表達式的應⽤案例,可以在⼀些特殊情況下使⽤:
列表排序:
a = [(1, 2), (4, 1), (9, 10), (13, -3)]
a.sort(key=lambda x: x[1])
print(a)
# Output: [(13, -3), (4, 1), (1, 2), (9, 10)]
2、Map
規範:
map(function_to_apply, list_of_inputs)
⼤多數時候,我們要把列表中所有元素⼀個個地傳遞給⼀個函數,並收集輸出。⽐⽅說:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
Map可以讓我們⽤⼀種簡單⽽漂亮得多的⽅式來實現。就是這樣:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
3、Filter
顧名思義,filter過濾列表中的元素,並且返回⼀個由所有符合要求的元素所構成的列表,符合要求即函數映射到該元素時返回值爲True. 這⾥是⼀個簡短的例⼦:
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
# Output: [-5, -4, -3, -2, -1]
這個filter類似於⼀個for循環,但它是⼀個內置函數,並且更快。
注意:如果map和filter對你來說看起來並不優雅的話,採用列表/字典/元組推導式,可讀性更好。
4、Reduce
當需要對⼀個列表進⾏⼀些計算並返回結果時,Reduce 是個⾮常有⽤的函數。舉個例⼦,當你需要計算⼀個整數列表的乘積時。通常在 python 中你可能會使⽤基本的 for 循環來完成這個任務。
現在我們來試試 reduce:
from functools import reduce
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
# Output: 24
摘自:《python進階》