Understanding generators in Python

前端 未结 12 1546
日久生厌
日久生厌 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:25

    There is no Java equivalent.

    Here is a bit of a contrived example:

    #! /usr/bin/python
    def  mygen(n):
        x = 0
        while x < n:
            x = x + 1
            if x % 3 == 0:
                yield x
    
    for a in mygen(100):
        print a
    

    There is a loop in the generator that runs from 0 to n, and if the loop variable is a multiple of 3, it yields the variable.

    During each iteration of the for loop the generator is executed. If it is the first time the generator executes, it starts at the beginning, otherwise it continues from the previous time it yielded.

提交回复
热议问题