1.获取移动平均值
def wrapper(fun): def inner(*args,**kwargs): ret=fun(*args,**kwargs) ret.__next__() return ret return inner @wrapper def g(): sum=0 count=0 avg=0 while True: num=yield avg sum+=num count+=1 avg=sum/count f=g() print(f.send(10)) print(f.send(20)) print(f.send(30))
2.处理文件:用户指定要查找的文件和内容
将文件中包含要查找内容的每一行都输出到屏幕
def search(): with open("a1.txt",encoding="utf-8") as f1: for i in f1: if "我" in i: yield i g=search() for i in g: print(i.strip())
3.写生成器,从文件中读取内容,在每一次读取到的内容之前加上‘***’之后再返回用户
def file_add(): with open("a1.txt",encoding="utf-8") as f1: for i in f1: yield "***"+i g=file_add() for i in g: print(i.strip())
4.面试题
def demo(): for i in range(4): yield i g=demo() g1=(i for i in g) g2=(i for i in g1) print(list(g1)) print(list(g2)) 面试题1
def add(n,i): return n+i def test(): for i in range(4): yield i g=test() for n in [1,10]: g=(add(n,i) for i in g) print(list(g))
import os def init(func): def wrapper(*args,**kwargs): g=func(*args,**kwargs) next(g) return g return wrapper @init def list_files(target): while 1: dir_to_search=yield for top_dir,dir,files in os.walk(dir_to_search): for file in files: target.send(os.path.join(top_dir,file)) @init def opener(target): while 1: file=yield fn=open(file) target.send((file,fn)) @init def cat(target): while 1: file,fn=yield for line in fn: target.send((file,line)) @init def grep(pattern,target): while 1: file,line=yield if pattern in line: target.send(file) @init def printer(): while 1: file=yield if file: print(file) g=list_files(opener(cat(grep('python',printer())))) g.send('/test1') 协程应用:grep -rl /dir tail&grep