美文网首页
9-2 自定义生成器

9-2 自定义生成器

作者: 正在努力ing | 来源:发表于2018-08-26 15:37 被阅读0次
    一个生成器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
    
    

    相关文章

      网友评论

          本文标题:9-2 自定义生成器

          本文链接:https://www.haomeiwen.com/subject/ttyoiftx.html