python学习笔记—— 函数
〈p>读取远程页面
from urllib import urlretrieve def printFile(url): f = open(url) for line in f: if line.strip(): print line f.close() def loadFile(url=r'http://www.idkin.com/contact.html', process=printFile): try: fileName = urlretrieve(url,'tmp.html')[0] print(fileName) except BaseException, e: print(str(e)) if fileName: process(fileName) if __name__ == "__main__": loadFile() #urlretrieve的返回值是一个tuple, 第一个元素就是目标文件名 #如果urlretrieve仅获取一个参数,返回值的第一个元素就是产生的临时文件名
filter函数,类似javascript1.7的Array#filter。filter函数的功能相当于过滤器。调用一个布尔函数fn来迭代遍历每个seq中的元素;返回一个使fn返回值为true的元素的序列。
from random import randint def filter(fn,arr): ret = []; for i in arr: if fn(i): ret.append(i) return ret; arr = [1,2,3,4,5,6]; print filter(lambda n:n%2,arr)
map函数,类似javascript1.7的Array#map。map函数func作用于给定序列的每个元素,并用一个列表来提供返回值。
from random import randint def map(fn,arr): ret = []; for i in arr: ret.append(fn(i)) return ret; arr = [1,2,3,4,5,6]; print map(lambda n:n+10,arr)
我们也可以用并归的思想实现此迭代器:
def rmap ( fun, list ): if list == []: return [] else: return [fun( list[0] )] + rmap( fun, list[1:] )
reduce函数,类似javascript1.7的Array#reduce。fn为二元函数,将fn作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值。
from random import randint def reduce(fn,seq,initial=None): lseq = list(seq) if initial is None: res = lseq.pop(0) else: res = initial for i in lseq: res = fn(res,i) return res arr = [1,2,3,4,5,6]; print reduce(lambda a,b:a+b,arr)
追踪闭包词法的变量
output = 'int %r id=%#0x val=%d' w = x = y =z =1 def f1(): x = y = z = 2 def f2(): y = z = 3 def f3(): z = 4 print output %('w', id(w),w) print output %('x', id(x),x) print output %('y', id(y),y) print output %('z', id(z),z) clo = f3.func_closure if clo: print "f3 closure vars: ",[str(c) for c in clo] else: print "no f3 closure vars" f3() clo = f2.func_closure if clo: print "f2 closure vars: ",[str(c) for c in clo] else: print "no f2 closure vars" f2() clo = f1.func_closure if clo: print "f1 closure vars: ",[str(c) for c in clo] else: print "no f1 closure vars" f1()
打印日志
# coding='utf-8' from time import time def logged(when): def log(f,*args,**kargs): print '''Called: function:%s args:%r kargs:%r''' % (f,args,kargs) def pre_logged(f): def wrapper(*args,**kargs): log(f,*args,**kargs) return f(*args,**kargs) return wrapper def post_logged(f): def wrapper(*args,**kargs): now=time() try: return f(*args,**kargs) finally: log(f,*args,**kargs) print "time delta: %s" %(time()-now) return wrapper try: return {"pre":pre_logged,"post":post_logged}[when] except KeyError, e: raise ValueError(e),'must be "pre" or "post"' @logged("post") def hello(name): print "Hello,",name hello("World")
生成器
# coding='utf-8' def counter(start_at=10): count = start_at while(True): val = (yield count) if(val is not None): count = val else: count += 1 if(count == 10): break for i in counter(3): print i
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年