zoukankan      html  css  js  c++  java
  • 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()
     
     
     
     
  • 相关阅读:
    Codeforces Round #371 (Div. 1)
    Making the Grade(POJ3666)
    The trip(Uva 11100)
    Codeforces Round #370 (Div. 2) E. Memory and Casinos (数学&&概率&&线段树)
    [CodeForces
    勾股数组 学习笔记
    NOIP 2015 游记
    BestCoder Round #53 (div.1)
    北大信息学夏令营 游记
    Codeforces Round #313 (Div. 1)
  • 原文地址:https://www.cnblogs.com/myshuzhimei/p/11757194.html
Copyright © 2011-2022 走看看