生成器不断返回相同的值 [英] generator keeps returning the same value
问题描述
我被困在这一段代码上,因为我无法让生成器每次调用它时都将下一个值返回给我-它只停留在第一个值上!看看:
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:
从numpy导入*
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
这就是我得到的:
>>> 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!
推荐答案
每次调用ArrayCoords(20,20)
时,它都会返回一个新的生成器对象,该生成器对象与您每调用一次ArrayCoords(20,20)
所返回的生成器对象不同.要获得所需的行为,您需要保存生成器:
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)
这篇关于生成器不断返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!