将收益生成器添加到 python 函数

Add yield generator to python function

我有这个问题陈述:

为获得最佳性能,应分批处理记录。 创建一个生成器函数 "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 生成器的新手,这根本不会在控制台上显示任何内容,没有错误,什么都没有,有什么想法吗?

生成器是懒惰的,应该消耗或 bootstrap 它才能做某事。

参见示例:

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 错误,因此您应该捕获或抑制它