首页 > 编程语言 > 详细

python高级特性-生成器

时间:2017-09-06 15:07:02      阅读:179      评论:0      收藏:0      [点我收藏+]

在python中一边循环一边计算的机制成为生成器(generator)

在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

生成list

>>> L=[x*x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

生成generator

>>> G=(x*x for x in range(10))
>>> G
<generator object <genexpr> at 0x7f5cc1ce3c80>

两者的区别就在于最外层的[]和(),L是一个list,而g是一个generator

yield生成器

 

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

>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

 

python高级特性-生成器

原文:http://www.cnblogs.com/yaohong/p/7484602.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!