• yield生成器


     
    >>一个带有 yield 的函数就是一个 generator,它和普通函数不同。
    >>生成一个 generator 看起来像函数调用,但不会执行任何函数代码,直到对其调用 next()才开始执行。
    >>每执行到一个 yield 语句就会中断,并返回一个迭代值,下次执行时从 yield 的下一个语句继续执行。
    >>yield 的好处是显而易见的:具有迭代能力,可复用性好,空间占用不浪费,代码简洁,执行流程异常清晰。
     
    可以通过比较下面两种代码,感受yield在空间占用这块的优势。
    range代码
    print type(range(10))  
    print (range(10)) 
    for i in range(10):
        if i%2==0:
           print i
     
    输出:
    type 'list'
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    0
    2
    4
    6
    8
     
    yield代码
    def foo(num):
        while num<10:       
           yield num
           num=num+2
           
    print type(foo(0))
    print (foo(0))
    for n in foo(0):
        print(n)
     
    输出:
    type 'generator'
    generator object foo at 0x0000000009A18DC8
    0
    2
    4
    6
    8
     
    在 for 循环中会自动调用 next():
    上面的
    for n in foo(0):
        print(n)
    等价于    
    g=foo(0)
    print next(g)  
    print next(g)
    print next(g)
    print next(g)
    print next(g)
     
    print next(g)也可以写作print g.next()
    注意不能写成print next(foo(0))  或者print foo(0).next()
     
     
     
     
  • 相关阅读:
    centos7中Apache,MySQL,php安装和项目
    centos7中Apache,MySQL,php安装
    tp5中index.php的隐藏
    php打印
    绝对与相对的区别
    tinkphp框架中config.php中数组中参数的意义
    tinkphp框架开启调试
    获取唯一随机数
    如何在magento中建立自定义页面
    获取用户邮寄地址
  • 原文地址:https://www.cnblogs.com/myshuzhimei/p/11757194.html
Copyright © 2020-2023  润新知