map/reduce/filter 是 Python 中較為常用的內(nèi)建高階函數(shù),它們?yōu)楹瘮?shù)式編程提供了不少便利。
map 函數(shù)的使用形式如下:
map(function, sequence)
解釋:對 sequence 中的 item 依次執(zhí)行 function(item),并將結(jié)果組成一個 List 返回,也就是:
[function(item1), function(item2), function(item3), ...]
看一些簡單的例子。
>>> def square(x):
... return x * x
>>> map(square, [1, 2, 3, 4])
[1, 4, 9, 16]
>>> map(lambda x: x * x, [1, 2, 3, 4]) # 使用 lambda
[1, 4, 9, 16]
>>> map(str, [1, 2, 3, 4])
['1', '2', '3', '4']
>>> map(int, ['1', '2', '3', '4'])
[1, 2, 3, 4]
再看一個例子:
def double(x):
return 2 * x
def triple(x):
return 3 *x
def square(x):
return x * x
funcs = [double, triple, square] # 列表元素是函數(shù)對象
# 相當(dāng)于 [double(4), triple(4), square(4)]
value = list(map(lambda f: f(4), funcs))
print value
# output
[8, 12, 16]
上面的代碼中,我們加了 list 轉(zhuǎn)換,是為了兼容 Python3,在 Python2 中 map 直接返回列表,Python3 中返回迭代器。
reduce 函數(shù)的使用形式如下:
reduce(function, sequence[, initial])
解釋:先將 sequence 的前兩個 item 傳給 function,即 function(item1, item2),函數(shù)的返回值和 sequence 的下一個 item 再傳給 function,即 function(function(item1, item2), item3),如此迭代,直到 sequence 沒有元素,如果有 initial,則作為初始值調(diào)用。
也就是說:
reduece(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
看一些例子,就能很快理解了。
>>> reduce(lambda x, y: x * y, [1, 2, 3, 4]) # 相當(dāng)于 ((1 * 2) * 3) * 4
24
>>> reduce(lambda x, y: x * y, [1, 2, 3, 4], 5) # ((((5 * 1) * 2) * 3)) * 4
120
>>> reduce(lambda x, y: x / y, [2, 3, 4], 72) # (((72 / 2) / 3)) / 4
3
>>> reduce(lambda x, y: x + y, [1, 2, 3, 4], 5) # ((((5 + 1) + 2) + 3)) + 4
15
>>> reduce(lambda x, y: x - y, [8, 5, 1], 20) # ((20 - 8) - 5) - 1
6
>>> f = lambda a, b: a if (a > b) else b # 兩兩比較,取最大值
>>> reduce(f, [5, 8, 1, 10])
10
filter 函數(shù)用于過濾元素,它的使用形式如下:
filter(function, sequnce)
解釋:將 function 依次作用于 sequnce 的每個 item,即 function(item),將返回值為 True 的 item 組成一個 List/String/Tuple (取決于 sequnce 的類型,python3 統(tǒng)一返回迭代器) 返回。
看一些例子。
>>> even_num = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]))
>>> even_num
[2, 4, 6]
>>> odd_num = list(filter(lambda x: x % 2, [1, 2, 3, 4, 5, 6]))
>>> odd_num
[1, 3, 5]
>>> filter(lambda x: x < 'g', 'hijack')
'ac' # python2
>>> filter(lambda x: x < 'g', 'hijack')
<filter object at 0x1034b4080> # python3