【问题标题】:Why is this python generator function running correctly only once?为什么这个 python 生成器函数只能正确运行一次?
【发布时间】:2016-08-05 18:52:27
【问题描述】:

这几乎可以肯定是因为我对生成器的工作原理一无所知,但我完全迷失了。

如果我以交互方式创建以下生成器:

def neighborhood(iterable):
    iterator = iter(iterable)
    prev = None
    item = next(iterator) 
    for post in iterator:
        yield (prev,item,post)
        prev = item
        item = post
    yield (prev,item,None)

然后像这样测试它:

for prev,item,next in neighborhood([1,2,3,4,5]):
print(prev, item, next)

它产生:

None 1 2
1 2 3
2 3 4
3 4 5
4 5 None

正如预期的那样。如果我再次运行它,或者尝试以任何方式重新定义它,我会得到一个

'NoneType' 对象不可调用"

错误。

【问题讨论】:

    标签: python python-3.x generator


    【解决方案1】:

    什么时候做的

    for prev,item,next in ...
    #             ^^^^
    

    您隐藏了内置的 next 函数。下次您尝试使用生成器时,它会失败,因为它会获取您的 next 变量而不是它所需的函数。

    【讨论】:

    • 该死。是的。太傻了。
    【解决方案2】:

    这是因为您在测试代码中使用了一个名为 next 的变量。使用不影响内置函数 next 的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多