文章目錄
5 函數式編程
5.1 高階函數
變量指向函數:
>>> f = abs
>>> f(-10)
10
一個函數接收另一個函數作爲參數——高階函數:
def add(x, y, f):
return f(x) + f(y)
5.1.1 map/reduce
把函數f(x)=x2作用在一個list [1, 2, 3, 4, 5, 6, 7, 8, 9]上:
>>> 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']
對一個序列求和:
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
把序列[1, 3, 5, 7, 9]變換成整數13579:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
把str轉換爲int:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> def char2num(s):
... digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
... return digits[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579
str2int:
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return DIGITS[s]
return reduce(fn, map(char2num, s))
用lambda函數進一步簡化:
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(s):
return DIGITS[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
5.1.2 filter
在一個list中,刪掉偶數,只保留奇數:
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
把一個序列中的空字符串刪掉:
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 結果: ['A', 'B', 'C']
用filter求素數:
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
def _not_divisible(n):
return lambda x: x % n > 0
def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一個數
yield n
it = filter(_not_divisible(n), it) # 構造新序列
5.1.3 sorted
對list進行排序:
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
按絕對值大小排序:
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
字符串排序:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'])
['Credit', 'Zoo', 'about', 'bob']
忽略大小寫排序:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']
反向排序:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
5.2 返回函數
5.2.1 函數作爲返回值
可變參數的求和:
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
不返回求和的結果,而是返回求和的函數:
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
調用函數f時,才真正計算求和的結果:
>>> f()
25
5.2.2 閉包
引用循環變量:
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()
>>> f1()
1
>>> f2()
4
>>> f3()
9
5.3 匿名函數
計算f(x)=x2:
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
把匿名函數賦值給一個變量,再利用變量來調用該函數:
>>> f = lambda x: x * x
>>> f
<function <lambda> at 0x101c6ef28>
>>> f(5)
25
把匿名函數作爲返回值返回:
def build(x, y):
return lambda: x * x + y * y
5.4 裝飾器
函數對象被賦值給變量,通過變量調用該函數:
>>> def now():
... print('2015-3-25')
...
>>> f = now
>>> f()
2015-3-25
__name__屬性拿到函數的名字:
>>> now.__name__
'now'
>>> f.__name__
'now'
定義一個能打印日誌的decorator:
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
藉助Python的@語法,把decorator置於函數的定義處:
@log
def now():
print('2015-3-25')
自定義log的文本:
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def now():
print('2015-3-25')
3層嵌套的decorator用法:
@log('execute')
def now():
print('2015-3-25')
>>> now()
execute now():
2015-3-25
一個完整的decorator的寫法:
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
針對帶參數的decorator:
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
5.5 偏函數
int()函數把字符串轉換爲整數:
>>> int('12345')
12345
做N進制的轉換:
>>> int('12345', base=8)
5349
>>> int('12345', 16)
74565
int2() 函數,默認把base=2傳進去:
def int2(x, base=2):
return int(x, base)
直接使用下面的代碼創建一個新的函數int2:
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85