码迷,mamicode.com
首页 > 编程语言 > 详细

Python Generator

时间:2014-09-03 12:51:56      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   使用   ar   for   2014   

  本文对《Python Cookbook》中对于生成器部分的讲解进行总结和分析:

  对于生成器我们一般这样使用:

lxw Python_Cookbook$ p
Python 3.4.0 (default, Apr 11 2014, 13:05:18) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def countdown(n):
...     print("Start to count from", n)
...     while n > 0:
...          yield n
...          n -= 1
...     print("Done!")
... 
>>> c = countdown(3)
>>> c
<generator object countdown at 0xb7234c5c>
>>> for item in c:
...     print(item)
... 
Start to count from 3
3
2
1
Done!

  我想说的是, 让我们来看一下生成器的底层工作机制(underlying mechanics):[接上面的代码]

>>> d = countdown(3)
>>> d
<generator object countdown at 0xb711a43c>
>>> next(d)
Start to count from 3
3
>>> next(d)
2
>>> next(d)
1
>>> next(d)
Done!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

 

Python Generator

标签:style   blog   color   os   io   使用   ar   for   2014   

原文地址:http://www.cnblogs.com/lxw0109/p/python-generator.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!