generator and yield

If a function uses the yield keyword, it defines an object known as a generator. A generator is a function that produces a sequence of values for use in iteration.

1.
A generator function is a special kind of function that you can use to define your own iterators. When you define a generator function, you return each iteration's value using the yield keyword. When there are no more iterations, an empty return statement or flowing off the end of the function ends the iterations. Local variables in a generator function are saved from one call to the next, unlike in normal functions:

def four():
    x = 0
    while x < 4:
    print("in generator, x =", x)
    yield x
    x += 1

>>> for i in four():
    print(i)

in generator, x = 0
0
in generator, x = 1
1
in generator, x = 2
2
in generator, x = 3
3


>>> 2 in four()
in generator, x = 0
in generator, x = 1
in generator, x = 2
True
>>> 5 in four()
in generator, x = 0
in generator, x = 1
in generator, x = 2
in generator, x = 3
False


2.

def countdown(n):
    print("Counting down from %d" % n)
    while n > 0:
        yield n
        n -= 1
    #return

>>>c = countdown(10)

If you call this function, you will find that none of its code starts executing. For example:
>>> c = countdown(10)
>>>

Instead, a generator object is returned.The generator object, in turn, executes the function
whenever next() is called (or  __next__() in Python 3). 

Here's an example:
>>> c.next() # Use c.__next__() in Python 3
Counting down from 10
10
>>> c.next()
9

You can also use for statement to loop the generator object.
def countdown(n):
    print("Counting down from %d" % n)
    while n > 0:
        yield n
        n -= 1

c = countdown(10)
for i in c:
    print i


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值