Python2.x_函数式编程
变量可以指向函数,函数名也是变量
一 高阶函数:参数包含函数
def add(a, b, f):
print f(a)+f(b)
add(-3, 4, abs)
二 map函数:map(function, sequence, ...)
print map(lambda x:x*x, [0, 1, 2, 3, 4]) # [0, 1, 4, 9, 16]
三 reduce函数
reduce(function, sequence, initial), function必须只接受2个参数
reduce(f,[x1,x2,x3 x4])=f(f(x1,x2),x3),x4)
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 str2num(s):
return reduce(lambda x,y:10*x+y, map(char2num, s))
print str2num('232891739')+1
四 filter函数
filter(function, sequence), function必须返回bool值
若function返回True则保留,返回False则过滤
def biggerthan5(x):
return x>5
print filter(biggerthan5, [1,3,5,7,9])
五 sorted函数
sorted(iterable, cmp=None, key=None, reverse=False)
若reverse=False, 当cmp返回正数时,将左数移到右数右边
def sortCriterion1(x,y):#从小到大 ,less
if x>y:
return 1
elif x<y:
return -1
return 0
def sortCriterion2(x,y):#从大到小 ,greater
if x>y:
return -1
elif x<y:
return 1
return 0
print u'从小到大:',sorted([1,3,2], sortCriterion1)
print u'从大到小:',sorted([1,3,2], sortCriterion2)
六 闭包函数:返回值为函数
def name(s):
def score(n):
print s,'your score is',n
return score
n = name('Yoleimei')
n(100)
七 匿名函数lambda
lambda x,y: x*x+y*y == function(x,y){return x*x+y*y;} # in javascript
注:lambda表达式可嵌套,如 lambda fun1,fun2: lambda param: fun1(fun2(param))
def build(x, y):
return lambda: x * x + y * y
f = build(3,5)
print f()
八 装饰器Decorator:可以类比Decorator Design Pattern
def deco(fun):
print 'before calling fun()'
fun()
print 'after calling fun()'
return fun
@deco
def myFun():
print 'calling fun()'
# console:
# before calling fun()
# calling fun()
# after calling fun()
九 偏函数:使部分参数默认化
import functools
def add(x, y):
return x+y
myAdd = functools.partial(add, x=3, y=4)
print myAdd()