高階函數Higher-orderfunction
變量可以指向函數
>>> abs #abs(-10)是函數調用,而abs是函數本身
<built-in function abs>
>>> f = abs #函數本身也可以賦值給變量
>>> f #變量可以指向函數
<built-in function abs>
>>> f(-10) #變量調用函數
10
函數名也是變量
>>> abs = 10
>>> abs(-10) #把abs指向10后,無法通過abs(-10)調用該函數
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
傳入函數
既然變量可以指向函數,函數的參數能接收變量,那么一個函數就可以接收另一個函數作為參數,這種函數就稱之為高階函數。
>>> def add(x, y, f):
return f(x) + f(y)
>>> add(-1,-2,abs)
map
map()函數接收兩個參數,一個是函數,一個是序列,map將傳入的函數依次作用到序列的每個元素,并把結果作為新的list返回。舉例說明,比如我們有一個函數f(x)=x2,要把這個函數作用在一個list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()實現如下:
>>> def f(x):
return x * x
>>> map(f, [1, 2, 3, 4, 5, 6, 7,8, 9]) #第一個參數是f,即函數對象本身
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> map(str, [1, 2, 3, 4, 5, 6, 7,8, 9]) #把這個list所有數字轉為字符串
['1', '2', '3', '4', '5', '6', '7', '8','9']
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of asequence,from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). If initial isPResent, it is placed before the items of the sequence in the calculation, and serves as a default whenthe sequence is empty.
>>> def add(x, y):
return x + y
>>> reduce(add, [1, 3, 5, 7, 9])
25
def str2int(s):#把str轉換為str2int
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))
filter
filter(...)
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
def is_odd(n):#list中,刪掉偶數
return n % 2 == 1
filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
def not_empty(s):#序列中的空字符串刪掉
return s and s.strip()
filter(not_empty, ['A', '', 'B', None, 'C',' '])
sorted
sorted(iterable, cmp=None, key=None,reverse=False) --> new sorted list
>>> def reversed_cmp(x, y):#倒序排序
if x > y:
return -1
if x < y:
return 1
return 0
>>> sorted([36, 5, 12, 9, 21],reversed_cmp)
[36, 21, 12, 9, 5]
>>> def cmp_ignore_case(s1, s2):#忽略大小寫來比較兩個字符串
u1 = s1.upper()
u2 = s2.upper()
if u1 < u2:
return -1
if u1 > u2:
return 1
return 0
>>> sorted(['bob', 'about', 'Zoo','Credit'], cmp_ignore_case)
['about', 'bob', 'Credit', 'Zoo']
返回函數
def calc_sum(*args):#可變參數的求和
ax = 0
for n in args:
ax = ax + n
return ax
不需要立刻求和,而是在后面的代碼中,根據需要再計算.
def lazy_sum(*args):
def sum():#又定義了函數sum
ax = 0
for n in args:
ax = ax + n#引用外部函數lazy_sum的參數和局部變量
return ax#這種程序結構稱為“閉包
return sum
>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function sum at 0x10452f668>
>>> f()
25
>>> f1 = lazy_sum(1, 3, 5, 7, 9)
>>> f2 = lazy_sum(1, 3, 5, 7, 9)
>>> f1==f2#每次調用都會返回一個新的函數,結果互不影響
False
匿名函數
>>> map(lambda x: x * x, [1, 2, 3,4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]
匿名函數lambda x: x * x實際上就是:
def f(x):
return x * x
>>> f = lambda x: x * x#把匿名函數賦值給一個變量,再利用變量來調用該函數
>>> f
<function <lambda> at0x10453d7d0>
>>> f(5)
25
裝飾器
decorator就是一個返回函數的高階函數。所以,我們要定義一個能打印日志的decorator,可以定義如下:
def log(func):#decorator
def wrapper(*args, **kw):
print 'call %s():' % func.__name__
return func(*args, **kw)
return wrapper
@log#把decorator置于函數的定義處
def now():
print '2013-12-25'
>>> now()
call now():#運行now()函數前打印一行日志
2013-12-25
def log(text):#自定義log的文本
def decorator(func):
def wrapper(*args, **kw):
print '%s %s():' % (text,func.__name__)
return func(*args, **kw)
return wrapper
return decorator
@log('execute')#3層嵌套的decorator用法
def now():
print '2013-12-25'
偏函數Partial function
>>> int('12345', base=8)#傳入base參數,就可以做N進制的轉換
5349
def int2(x, base=2):#定義int2()函數,默認把base=2傳進去
return int(x, base)
>>> int2('1000000')
64
functools.partial就是幫助我們創建一個偏函數的,不需要我們自己定義int2(),可以直接使用下面的代碼創建一個新的函數int2:
>>> import functools
>>> int2 = functools.partial(int,base=2)
>>> int2('1000000')
64
functools.partial的作用就是,把一個函數的某些參數給固定住(也就是設置默認值),返回一個新的函數,調用這個新函數會更簡單。

求關注 求擴散
新聞熱點
疑難解答