zoukankan      html  css  js  c++  java
  • 生成器

    一、概念

    #只要函数内部包含有yield关键字,那么函数名()的到的结果就是生成器,并且不会执行函数内部代码
    def func():
        print('====>first')
        yield 1
        print('====>second')
        yield 2
        print('====>third')
        yield 3
        print('====>end')
    g=func()
    print(g) #<generator object func at 0x0000000002184360>
    # 生成器:自定义的迭代器
    # 函数内但凡出现yield关键字,再调用函数,不会触发函数体代码的运行
    # 会得到一个返回值,该返回值就是一个生成器对象,也就是自定义的迭代器
    二、yield与return的区别
    # yield与return
    # 相同点:都能返回值
    # 不同点:yield能返回多次值,而return只能返回一次值函数就立即结束
    三、练习
    #题目一:
    def my_range(start,stop,step=1):
        while start < stop:
            yield start
            start+=step
    
    #执行函数得到生成器,本质就是迭代器
    obj=my_range(1,7,2) #1  3  5
    print(next(obj))
    print(next(obj))
    print(next(obj))
    print(next(obj)) #StopIteration
    
    #应用于for循环
    for i in my_range(1,7,2):
        print(i)
    自定义函数模拟range(1,7,2)
    import time
    def tail(filepath):
        with open(filepath,'rb') as f:
            f.seek(0,2)
            while True:
                line=f.readline()
                if line:
                    yield line
                else:
                    time.sleep(0.2)
    
    def grep(pattern,lines):
        for line in lines:
            line=line.decode('utf-8')
            if pattern in line:
                yield line
    
    for line in grep('404',tail('access.log')):
        print(line,end='')
    
    #测试
    with open('access.log','a',encoding='utf-8') as f:
        f.write('出错啦404
    ')
    模拟管道,实现功能:tail -f access.log | grep '404'
     
     


    二、yield与return的区别
  • 相关阅读:
    【ORA-02049】超时分布式事务处理等待锁 解决方法
    Git使用出错:Couldn‘t reserve space for cygwin‘s heap, Win32
    JS身份证号码校验
    linux 下查看cpu位数 内核等参数命令(转)
    linux ps命令,查看进程cpu和内存占用率排序(转)
    JAVA图片验证码
    JAVA BigDecimal 小数点处理
    Linux命令大全
    Eclipse Java注释模板设置详解
    JSONArray的应用
  • 原文地址:https://www.cnblogs.com/datatool/p/13508522.html
Copyright © 2011-2022 走看看