Understanding generators in Python

前端 未结 12 1583
日久生厌
日久生厌 2020-11-21 05:46

I am reading the Python cookbook at the moment and am currently looking at generators. I\'m finding it hard to get my head round.

As I come from a Java background, i

12条回答
  •  無奈伤痛
    2020-11-21 06:13

    I put up this piece of code which explains 3 key concepts about generators:

    def numbers():
        for i in range(10):
                yield i
    
    gen = numbers() #this line only returns a generator object, it does not run the code defined inside numbers
    
    for i in gen: #we iterate over the generator and the values are printed
        print(i)
    
    #the generator is now empty
    
    for i in gen: #so this for block does not print anything
        print(i)
    

提交回复
热议问题