generator keeps returning the same value

十年热恋 提交于 2019-12-02 21:24:34

问题


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:

from numpy import *

def ArrayCoords(x,y,RowCount=0,ColumnCount=0):   # I am trying to get it to print
    while RowCount<x:                            # a new coordinate of a matrix
        while ColumnCount<y:                     # left to right up to down each
            yield (RowCount,ColumnCount)         # time it's called.
            ColumnCount+=1
        RowCount+=1
        ColumnCount=0

Here is what I get:

>>> next(ArrayCoords(20,20))
... (0, 0)
>>> next(ArrayCoords(20,20))
... (0, 0)

But it's just stuck on the first one! I expected this:

>>> next(ArrayCoords(20,20))
... (0, 0)
>>> next(ArrayCoords(20,20))
... (0, 1)
>>> next(ArrayCoords(20,20))
... (0, 2)

Could you guys help me out with the code as well as explain why it is so? Thank you in advance!


回答1:


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)



回答2:


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

iterator = ArrayCoords(20, 20)
next(iterator)
next(iterator)


来源:https://stackoverflow.com/questions/11279653/generator-keeps-returning-the-same-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!