码迷,mamicode.com
首页 > 其他好文 > 详细

生成器的使用demo

时间:2019-03-20 19:23:59      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:play   notice   for   ast   appear   recent   none   3.0   bsp   

 

定义一个函数:

def frange(start, stop, increment):
    x = start
    while x < stop:
        yield x
        x += increment

使用:

>>> for n in frange(0, 4, 0.5):
...     print(n)
...
0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
>>> list(frange(0, 1, 0.125))
[0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
>>>

 


 

demo:

>>> def countdown(n):
...     print(Starting to count from, n)
...     while n > 0:
...         yield n
...         n -= 1
...     print(Done!)
...

>>> # Create the generator, notice no output appears
>>> c = countdown(3)
>>> c
<generator object countdown at 0x1006a0af0>

>>> # Run to first yield and emit a value
>>> next(c)
Starting to count from 3
3

>>> # Run to the next yield
>>> next(c)
2

>>> # Run to next yield
>>> next(c)
1

>>> # Run to next yield (iteration stops)
>>> next(c)
Done!
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
StopIteration
>>>

 

生成器的使用demo

标签:play   notice   for   ast   appear   recent   none   3.0   bsp   

原文地址:https://www.cnblogs.com/sea-stream/p/10566815.html

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