python学习之路5-----------------------生成器

来源:互联网 发布:如何在淘宝上卖童装 编辑:程序博客网 时间:2024/05/12 12:11

生成器有两种实现方法:

第一种:

>>> G=(x*x for x in range(10))  #与列表生成式的区别就是把[]变成()
>>> G
<generator object <genexpr> at 0x000000000363C678>
>>> for i in G:
print(i)
0
1
4
9
16
25
36
49
64
81

第二中写法:使用 yield关键字:

>>> def odd():
print('step 1')
yield 1
print('step 2')
yield 2
print ('step 3')
yield 3



>>> o=odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
2
>>> next(o)
step 3
3
>>> 

0 0