我被这段代码卡住了,因为我不能让生成器在每次调用它的时候都返回下一个值--它只是停留在第一个值上!看一看:
从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)
但它只是卡在第一个!我预料到了:
>>> next(ArrayCoords(20,20))
... (0, 0)
>>> next(ArrayCoords(20,20))
... (0, 1)
>>> next(ArrayCoords(20,20))
... (0, 2)
你们能帮我写代码并解释为什么会这样吗?感谢您的评分
2条答案
按热度按时间wwwo4jvm1#
每次调用
ArrayCoords(20,20)
时,它都会返回一个新的生成器对象,与每次调用ArrayCoords(20,20)
时返回的生成器对象不同。要获得你想要的行为,你需要保存生成器:b1zrtrql2#
在每一行上创建一个新的生成器。试试这个: