-
函數(shù)概念
函數(shù)本身也可以賦值給變量陈瘦,即:變量可以指向函數(shù)解滓。函數(shù)名同時是變量
-
高階函數(shù)
一個函數(shù)就可以接收另一個函數(shù)作為參數(shù),該函數(shù)稱為“高階函數(shù)”
def add(x, y, f):
return f(x) + f(y)
x ==> -5
y ==> 6
f ==> abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11
-
map_reduce_filter_sorted
- map:map(f,[x1,x2,x3])=[f(x1),f(x2),f(x3)]
>>> def f(x):
... return x * x
...
>>> map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]
- reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> 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]
...
>>> reduce(fn, map(char2num, '13579'))
13579
- 整理成一個str2int的函數(shù)就是:
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))
- filter:和map()類似给赞,filter()也接收一個函數(shù)和一個序列初婆。和map()不同的時蓬坡,filter()把傳入的函數(shù)依次作用于每個元素,然后根據(jù)返回值是True還是False決定保留還是丟棄該元素磅叛。
#去除空的字符串
def not_empty(s):
return s and s.strip()
filter(not_empty, ['A', '', 'B', None, 'C', ' '])
# 結(jié)果: ['A', 'B', 'C']
- sorted:
#逆序輸出
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]
-
函數(shù)作為返回值
不返回函數(shù)的結(jié)果渣窜,而是返回具體的函數(shù),有關(guān)參數(shù)和變量都保存在返回的函數(shù)中宪躯,這種稱為“閉包(Closure)”。返回的函數(shù)并沒有立刻執(zhí)行位迂,而是直到調(diào)用了f()才執(zhí)行访雪,每次調(diào)用返回的函數(shù)都屬于不同的對象。
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print("f1:%s,f2:%s,f3:%s" % (f1(), f2(), f3()))
#結(jié)果 f1:9,f2:9,f3:9
返回函數(shù)不要引用任何循環(huán)變量掂林,或者后續(xù)會發(fā)生變化的變量臣缀。
優(yōu)化:再創(chuàng)建一個函數(shù),用該函數(shù)的參數(shù)綁定循環(huán)變量當(dāng)前的值泻帮,無論該循環(huán)變量后續(xù)如何更改精置,已綁定到函數(shù)參數(shù)的值不變÷嘣樱可以這樣理解為上一個返回的函數(shù)參數(shù)仍為引用脂倦,并未直接返回值
def counts():
fs=[]
for i in range(1,4):
def f(j):
def g():
return j*j
return g
fs.append(f(i))
return fs
f4, f5, f6 = counts()
print("f1:%s,f2:%s,f3:%s" % (f4(), f5(), f6()))