【问题标题】:printing and writing out a generator object打印并写出生成器对象
【发布时间】:2020-08-20 22:13:45
【问题描述】:

尝试将生成器对象合并到我的代码中,但它无法正常工作。

def get_data():
    data = some_api_call
    result = data.json()
    return result

结果如下所示,其中每个 {} 都在新行上:

{u'bytes_out': 1052.0, u'host': u'abc.com'}
{u'bytes_out': 52.0, u'host': u'def.com'}
{u'bytes_out': 5558.0, u'host': u'xya.com'}
...


def write_to_file(line):
    #replacing the write statement with a print for testing
    print(line)

def read_report(data):
    for line in data:
        yield line

def main():
    alldata = get_data()
    write_to_file(read_report(alldata))

我的期望是它应该打印出来:

{u'bytes_out': 1052.0, u'host': u'abc.com'}
{u'bytes_out': 52.0, u'host': u'def.com'}
{u'bytes_out': 5558.0, u'host': u'xya.com'}

但我得到的是:

<generator object read_report at 0x7fca02462a00>

不知道我在这里缺少什么

*** 编辑 - 修复了我使用不正确的问题

def main():
    all_data = get_data()
    for line in read_report(all_data)
        print(line)

【问题讨论】:

  • read_report 返回一个生成器。你为什么感到惊讶?
  • 虽然print 将为您调用str 的参数,但generator.__str__ 不会通过迭代实例来构建字符串;它返回一个没有任何迭代的通用表示。
  • @DYZ 因为我错误地认为它会打印出生成器对象的 1 行我需要做什么才能获得预期的结果?
  • 迭代器是可以循环的东西。这个生成器本质上是一个迭代器。

标签: python generator


【解决方案1】:

您也可以直接从生成器打印:

gen = range(1,10)
print(*gen, flush=True)
#out: 1 2 3 4 5 6 7 8 9

所以你的情况:

print(*read_report(all_data), flush=True)

【讨论】:

  • 整洁,冲洗是做什么的?
  • 基本上它强制从缓冲区打印。您可以在此处阅读更多信息:stackoverflow.com/questions/15608229/what-does-prints-flush-do 在您的情况下,它甚至可能没有必要,在没有冲洗的情况下尝试一下。
  • 这违背了使用生成器的目的,因为您必须在 print 存在之前在内存中生成整个序列。
  • @chepner 是的,但在他的示例中,他无论如何都将其用于打印。
  • 所以?您可以逐行打印输出,而无需先将每一行读入内存。
猜你喜欢
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 2016-02-05
  • 2014-09-24
  • 1970-01-01
相关资源
最近更新 更多