【问题标题】:generator keeps returning the same value生成器不断返回相同的值
【发布时间】:2012-07-02 00:57:18
【问题描述】:

我被困在这段代码上,因为我无法让生成器在每次调用它时都返回下一个值——它只是停留在第一个值上!看看:

从 numpy 导入 *

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)

你们能帮我写代码并解释为什么会这样吗? 提前谢谢!

【问题讨论】:

    标签: generator yield next


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2010-09-22
        • 2020-09-07
        • 2023-03-26
        • 2021-10-07
        • 2015-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多