一個(gè)函數(shù)就可以接收另一個(gè)函數(shù)作為參數(shù)嗅剖,這種函數(shù)就稱之為高階函數(shù)。
def add(x, y, f):
return f(x) + f(y)
>>> add(-5, 6, abs)
11
推倒過程:
x = -5
y = 6
f = abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11
return 11
編寫高階函數(shù),就是讓函數(shù)的參數(shù)能夠接收別的函數(shù)衬鱼。
map/reduce
map()函數(shù)接收兩個(gè)參數(shù),一個(gè)是函數(shù)憔杨,一個(gè)是Iterable鸟赫,map將傳入的函數(shù)依次作用到序列的每個(gè)元素,并把結(jié)果作為新的Iterator返回消别。
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
r是一個(gè)Iterator抛蚤,Iterator是惰性序列,因此通過list()函數(shù)讓它把整個(gè)序列都計(jì)算出來并返回一個(gè)list
reduce把一個(gè)函數(shù)作用在一個(gè)序列[x1, x2, x3, ...]上寻狂,這個(gè)函數(shù)必須接收兩個(gè)參數(shù)岁经,reduce把結(jié)果繼續(xù)和序列的下一個(gè)元素做累積計(jì)算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
str也是一個(gè)序列蛇券,因此結(jié)合map和reduce方法可以方便的實(shí)現(xiàn)str2int函數(shù)
from functools import reduce
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
return reduce(fn, map(char2num, s))
使用lambda進(jìn)一步簡(jiǎn)化
from functools import reduce
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
filter
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 結(jié)果: [1, 5, 9, 15]
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 結(jié)果: ['A', 'B', 'C']
sorted
Python內(nèi)置的sorted()函數(shù)就可以對(duì)list進(jìn)行排序:
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
sorted()函數(shù)也是一個(gè)高階函數(shù)缀壤,它還可以接收一個(gè)key函數(shù)來實(shí)現(xiàn)自定義的排序,例如按絕對(duì)值大小排序:
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
字符串排序:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'])
['Credit', 'Zoo', 'about', 'bob']
默認(rèn)情況下纠亚,對(duì)字符串排序塘慕,是按照ASCII的大小比較的,由于'Z' < 'a'蒂胞,結(jié)果图呢,大寫字母Z會(huì)排在小寫字母a的前面。
忽略大小寫的排序:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']
要進(jìn)行反向排序啤誊,不必改動(dòng)key函數(shù)岳瞭,可以傳入第三個(gè)參數(shù)reverse=True:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']