python基础-生成器

1.什么是生成器:只要在函数内部出现yield关键字,那么再执行函数就不会执行函数代码,会得到一个结果,该结果就是生成器

                            生成器就是迭代器

2.yield的功能:

    1.yield为我们提供了一种自定义迭代器对象的方法

    2.yield与return的区别1.yield可以返回多次值  2.函数暂停与再继续的状态是由yield帮我们保存的

3.例子1:def my_range(start,stop,step=1):

                     while start<stop:

                             yield start#暂停在这后返回,再继续执行代码

                             start=start+step

              for i in my_range(0,10):

       print(i)

4.例子2:

import os

def fun_next(func):
def wapper(*args,**kwargs):
g=func(*args,**kwargs)
next(g)
return g
return wapper
@fun_next
def search(target):#拿到目录下的所有文件
filepath=yield
g=os.walk(filepath)
for pardir,_,files in g:
for file in files:
abs_path=r"%s\%s"%(pardir,file)
target.send(abs_path)
@fun_next
def opener(target):#打开所有文件
while True:
abs_path=yield
with open(abs_path) as f:
target.send((abs_path,f))
@fun_next
def cat(target):#拿到文件中的内容
while True:
abs_path,f=yield
for line in f:
res=target.send((abs_path,line))
if res:
break
@fun_next
def grep(target,pattern):#对内容进行过滤
res=False
while True:
abs_path,line=yield res
res=False
if pattern in line:
res=True
target.send(abs_path)
@fun_next
def printer():#打印符合条件的路径
abs_path=yield
print('<%s>'%abs_path)
def run(filepath):
while True:
try:
g=search(opener(cat(grep(printer(),pattern='python'))))
g.send(filepath)
except StopIteration:
break
run(r'E:\a')
posted @ 2019-12-11 17:14  birdfish  阅读(250)  评论(0编辑  收藏  举报