Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数
高阶函数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,9]) #第一个参数是f,即函数对象本身 [1,9,16,25,36,49,64,81] ? >>> map(str,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,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,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,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,12,21],reversed_cmp) [36,21,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,9) >>> f <function sum at 0x10452f668> >>> f() 25 >>> f1 = lazy_sum(1,9) >>> f2 = lazy_sum(1,9) >>> f1==f2#每次调用都会返回一个新的函数,结果互不影响 False ? 匿名函数 ? >>> map(lambda x: x * x,9]) [1,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的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。 求关注 求扩散 (编辑:北几岛) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |