1

我有这个问题陈述:

为获得最佳性能,应分批处理记录。创建一个生成器函数“batched”,一次将产生 1000 条记录的批次,可以按如下方式使用:

  for subrange, batch in batched(records, size=1000):
      print("Processing records %d-%d" %(subrange[0], subrange[-1]))
      process(batch)

我试过这样:

def myfunc(batched):
    for subrange, batch in batched(records, size=1000):
        print("Processing records %d-%d" %
        (subrange[0], subrange[-1]))
     yield(batched)

但我不确定,因为我是 python 生成器的新手,这根本不会在控制台上显示任何内容,没有错误,什么都没有,有什么想法吗?

4

1 回答 1

2

生成器是懒惰的,应该消耗或引导它以便它做某事。

参见示例:

def g():
    print('hello world')
    yield 3

x = g() # nothing is printed. Magic..

应该这样做:

x = g()
x.send(None) # now will print

或者:

x = g()
x.next()

[编辑]

请注意,当.next()显式执行时,最终你会得到StopIteration错误,所以你应该抓住它或抑制它

于 2018-12-16T19:35:41.803 回答