• python3(十一)generator


    # 只要把一个列表生成式的[]改成()
    L = [x * x for x in range(10)]
    print(L)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    g = (x * x for x in range(10))
    print(g)  # <generator object <genexpr> at 0x00000000021789C8>
    # print(next(g))  # 0
    # print(next(g))  # 1
    # print(next(g))  # 4
    # print(next(g))  # 9
    # generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,
    # 直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。
    # generator也是可迭代
    for n in g:
        print(n)
    
    
    # 0
    # 1
    # 4
    # 9
    # 16
    # 25
    # 36
    # 49
    # 64
    # 81
    # 创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误。
    def fib(max):
        n, a, b = 0, 0, 1
        while n < max:
            print(b)
            a, b = b, a + b
            n = n + 1
        return 'done'
    
    
    fib(8)
    
    
    # 如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
    def fib(max):
        n, a, b = 0, 0, 1
        while n < max:
            yield b
            a, b = b, a + b
            n = n + 1
        return 'done'
    
    
    # ---------------------------------------------------------------------
    #  generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
    # ---------------------------------------------------------------------
    def odd():
        print('step 1')
        yield 1
        print('step 2')
        yield (3)
        print('step 3')
        yield (5)
    
    
    # odd是generator,在执行过程中,遇到yield就中断,下次又继续执行。执行3次yield后,已经没有yield可以执行了,所以,第4次调用next(o)就报错。
    # 但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:
    g = fib(5)
    while 1:
        try:
            x = next(g)
            print('g:', x)
        except StopIteration as e:
            print('Generator return value:', e.value)
            break
  • 相关阅读:
    cpu capacity、task_util、cpu_util是如何计算的?
    QTI EAS学习之find_energy_efficient_cpu
    Linux内核进程调度overview(1)
    Ondemand和Interactive gonernor工作逻辑简述
    利用init进程监控底层节点的方法架构
    Sched_Boost小结
    SchedTune
    Cpusets学习
    搭建SpringCloud微服务框架:三、读取Nacos的配置信息
    搭建SpringCloud微服务框架:一、结构和各个组件
  • 原文地址:https://www.cnblogs.com/shaozhiqi/p/11543570.html
Copyright © 2020-2023  润新知