How to get one value at a time from a generator function in Python?

前端 未结 6 1956
鱼传尺愫
鱼传尺愫 2020-12-24 04:08

Very basic question - how to get one value from a generator in Python?

So far I found I can get one by writing gen.next(). I just want to make sure this

6条回答
  •  执念已碎
    2020-12-24 04:50

    Use (for python 3)

    next(generator)
    

    Here is an example

    def fun(x):
        n = 0
        while n < x:
            yield n
            n += 1
    z = fun(10)
    next(z)
    next(z)
    

    should print

    0
    1
    

提交回复
热议问题