【问题标题】:unexpected output when using next(generator)使用下一个(生成器)时的意外输出
【发布时间】:2020-10-15 06:56:44
【问题描述】:

代码如下:

from typing import Any, Generator, List, Set, Union
stream_type = Union[List[Any], str]

def valid_posts(stream: Generator[stream_type, None, None]) -> Set[int]:
    result = set()
    for post in stream():
        if post == "end_of_session":
            yield result
            result = set()       
            continue
        if post[2] == "hello":
            result.add(post[1])    
            

def stream():
    data = [
        [1, 1, "hello"],
        [1, 1, "world"],
        [1, 2, "hello"],
        [1, 2, "world"],
        [1, 3, "hello"],
        [1, 3, "world"],
        [1, 1, "hello"],
        [1, 1, "world"],
        "end_of_session",
        [2, 1, "hello"],
        [2, 1, "world"],
        [2, 2, "world"],
        [2, 2, "world"],
        [2, 3, "world"],
        [2, 3, "world"],
        "end_of_session",
    ]
    for item in data:
        yield item


# for post in valid_posts(stream):
#     print(post)
print(next(valid_posts(stream)))
print(next(valid_posts(stream)))
print(next(valid_posts(stream)))
print(next(valid_posts(stream)))

当我使用现在已注释掉的两行 (for post in valid_posts(stream): print(post)) 时,它会打印出预期的结果:

{1, 2, 3}
{1}

但是当我使用 print(next(valid_posts(stream))) 的四行时,它令人惊讶地打印出这些:

{1, 2, 3}
{1, 2, 3}
{1, 2, 3}
{1, 2, 3}

我的理解是我们可以使用next() 调用生成器,它会一个接一个地产生结果,但是为什么在这种情况下它只是重复打印第一个结果呢?谢谢

【问题讨论】:

  • 将此代码复制粘贴到 Pycharm 中会突出显示 for post in stream(): 中的 stream() in valid_posts,表示 'Generator' object is not callable...

标签: python python-3.x generator


【解决方案1】:

当您执行for post in valid_posts(stream): 时,您实际上是这样做的:

vp = valid_posts(stream) # save the iterator returned from valid_posts
print(next(vp))
print(next(vp))
print(next(vp))
print(next(vp))
# ... a until StopIteration is raised

在您的使用中,您一遍又一遍地调用valid_posts,而不是使用相同的迭代器。

编辑:
请注意,您也有严重的类型错误。
类型注释只是提示,当我将您的代码粘贴进去时,PyCharm 会尖叫起来。
注释存在并且代码运行的事实并不意味着代码符合注释。

【讨论】:

  • 很抱歉多次编辑,我第一次得到了您误解的“根本原因”错误......
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2016-07-29
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多