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()
 
 
 
 
posted @ 2019-10-29 10:12  数之美  阅读(433)  评论(0编辑  收藏  举报