一个生成器generator:一遍循环,一遍计算;需要下一个值时,才会计算,所以生成器就会节约内存
\ \ 普通函数是碰到return就会返回
\ \ 生成器是碰到yield返回,但是函数并没结束,此时会建立一个栈帧指向这里;指导主函数调用生成器的next(),生成器会找到这个栈帧,读取恢复现场,继续从上次yield结束位置运行
def myreadfile(f, newline):
buf = "" #读取内容缓存
while True:
while newline in buf: #缓存中存在分隔符
pos = buf.index(newline) #定位分隔符位置
yield buf[:pos] # 输出分隔符之前的内容
buf = buf[pos+len(newline):] #buf 变成分隔符之后的内容,再次循环
next_read = f.read(4096) # buf中不在有分隔符,就需要添加下次内容了
if not next_read: #没有读到下次的内容,证明文件读取完毕
yield buf
break
buf = buf+next_read
with open("test.txt") as f:
for line in myreadfile(f, "{|}"):
print(line)
>>>
Prior to beginning tutoring sessions
, I ask new students to fill
out a brief self-assessment
where they rate their
understanding of various Python concepts. Some topics ("control flow with if/else" or "defining and using functions") are understood by a majority of students before ever beginning tutoring. There are a handful of topics, however, that almost all
students report having no knowledge or very limited understanding of. Of these
网友评论