#函數式編程的一個特色就是,容許把函數自己做爲參數傳入另外一個函數,還容許返回一個函數 #編寫高階函數,就是讓函數的參數可以接收別的函數 def add(x, y, f): return f(x) + f(y) print(add(-1, 1, abs)) def f(x): return x * x r = map(f, [1, 2, 3, 4, 5]) print(list(r)) #map()函數接收兩個參數,一個是函數,一個是Iterable, #map將傳入的函數依次做用到序列的每一個元素,並把結果做爲新的Iterator返回 #reduce把一個函數做用在一個序列[x1, x2, x3, ...]上,這個函數必須接收兩個參數, #reduce把結果繼續和序列的下一個元素作累積計算 from functools import reduce def add(x, y): return x + y print(reduce(add, [1, 3, 5, 7, 9])) #13579 def fn(x, y): return x * 10 + y print(reduce(fn, [1, 3, 5, 7, 9])) 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] print(reduce(fn, map(char2num, '13579'))) #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)) #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))
和map()相似,filter()也接收一個函數和一個序列。和map()不一樣的時,filter()把傳入的函數依次做用於每一個元素,而後根據返回值是True仍是False決定保留仍是丟棄該元素編程
print(sorted([36, 5, -12, 9, -21])) print(sorted([36, 5, -12, 9, -21], key=abs)) print(sorted(['bob', 'about', 'Zoo', 'Credit'])) print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))
def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum f = lazy_sum(1, 3, 5, 7, 9) print(f()) def count(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)馬上被執行,所以i的當前值被傳入f() return fs f1, f2, f3 = count() print(f1()) print(f2()) print(f3())
#匿名函數 print(list(map(lambda x: x*x, [1, 2, 3]))) #匿名函數有個限制,就是隻能有一個表達式,不用寫return,返回值就是該表達式的結果 #def f(x): # return x * x
#def log(func): # @functools.wraps(func) # def wrapper(*args, **kw): # print('call %s():' % func.__name__) # return func(*args, **kw) # return wrapper import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator #@log @log('execute') def now(): print('2015-3-25') f = now f() print(now.__name__) print(f.__name__) #把@log放到now()函數的定義處,至關於執行了語句:now = log(now)
print(int('12345')) print(int('12345', base=8)) print(int('12345', 16)) #def int2(x, base=2): # return int(x, base) #print(int2('10000000000')) #轉換二進制 import functools int2 = functools.partial(int, base=2) print(int2('100000')) print(int2('100000', base=10)) #建立偏函數時,實際上能夠接收函數對象、*args和**kw這3個參數 max2 = functools.partial(max, 10) print(max2(2))