本文共 2061 字,大约阅读时间需要 6 分钟。
概念:
迭代的概念:重复+上一次迭代的结果为下一次迭代的初始值重复的过程称为迭代,每次重复即一次迭代,并且每次迭代的结果是下一次迭代的初始值可迭代对象:只有iter方法,执行该方法得到的迭代器对象
迭代协议:
对象有next对象有iter,对于迭代器对象来说,执行iter方法,得到的结果仍然是它本身可以作为for 循环的被循环体 都是可迭代对象;
li=[1,2,3,4,5]a=li.__iter__() -->生成迭代器print (a.__next__())print (a.__next__())print (a.__next__())print (a.__next__())
上面和
for i in li:print (i)是一样的,只不过 for 循环 捕捉了 报错,然后停掉了迭代器的优点和缺点
优点:1.提供了一种不依赖下标的迭代方式2.就跌迭代器本身来说,更节省内存缺点:
#生成器函数:只要函数体包含yield关键字,该函数就是生成器函数
#生成器就是迭代器def A(): print ('----1') yield 1 print ('-----2') yield 2 print ('-------3') yield 3JG=A()print (JG.__next__())print (JG.__next__())print (JG.__next__())
yield和return 相比 同样是返回值
但是 return 相当于break 而yield 还可以通过 next 方法调用下面import osdef init(func): def wrapper(*args,**kwargs): res=func(*args,**kwargs) next(res) return res return wrapper@initdef search(target): while True: search_path=yield g=os.walk(search_path) for par_dir,_,files in g: for file in files: file_abs_path=r'%s\%s' %(par_dir,file) # print(file_abs_path) target.send(file_abs_path)@initdef opener(target): while True: file_abs_path=yield # print('opener func==>',file_abs_path) with open(file_abs_path,encoding='utf-8') as f: target.send((file_abs_path,f))@initdef cat(target): while True: file_abs_path,f=yield #(file_abs_path,f) for line in f: tag=target.send((file_abs_path,line)) if tag: break@initdef grep(target,pattern): tag=False while True: file_abs_path,line=yield tag tag=False if pattern in line: tag=True target.send(file_abs_path)@initdef printer(): while True: file_abs_path=yield print(file_abs_path)x=r'C:\Users\Administrator\PycharmProjects\day5\a'g=search(opener(cat(grep(printer(),'python'))))print(g)g.send(x)
转载于:https://blog.51cto.com/ondali/2317926