generator keeps returning the same value

后端 未结 2 502
刺人心
刺人心 2021-01-28 06:41

I am stuck on this one piece of code because I can\'t get the generator to return me a the next value every time its called – it just stays on the first one! Take a look:

<
相关标签:
2条回答
  • 2021-01-28 07:20

    You create a new generator on every line. Try this instead:

    iterator = ArrayCoords(20, 20)
    next(iterator)
    next(iterator)
    
    0 讨论(0)
  • 2021-01-28 07:33

    Each time you call ArrayCoords(20,20) it returns a new generator object, different to the generator objects returned every other time you call ArrayCoords(20,20). To get the behaviour you want, you need to save the generator:

    >>> coords = ArrayCoords(20,20)
    >>> next(coords)
    (0, 0)
    >>> next(coords)
    (0, 1)
    >>> next(coords)
    (0, 2)
    
    0 讨论(0)
提交回复
热议问题