numpy generator返回相同的值

iqxoj9l9  于 2023-05-17  发布在  其他
关注(0)|答案(2)|浏览(130)

我被这段代码卡住了,因为我不能让生成器在每次调用它的时候都返回下一个值--它只是停留在第一个值上!看一看:
从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)

你们能帮我写代码并解释为什么会这样吗?感谢您的评分

wwwo4jvm

wwwo4jvm1#

每次调用ArrayCoords(20,20)时,它都会返回一个新的生成器对象,与每次调用ArrayCoords(20,20)时返回的生成器对象不同。要获得你想要的行为,你需要保存生成器:

>>> coords = ArrayCoords(20,20)
>>> next(coords)
(0, 0)
>>> next(coords)
(0, 1)
>>> next(coords)
(0, 2)
b1zrtrql

b1zrtrql2#

在每一行上创建一个新的生成器。试试这个:

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

相关问题