我想对输入流进行分块以进行批处理。给定一个输入列表或生成器,
它可以被分成固定大小的块,以便逐个块地处理它们。x_in = [1, 2, 3, 4, 5, 6 ...]
我希望有一个函数可以返回输入的块。比如,如果 chunk_size=4
,那么,
x_chunked = [[1, 2, 3, 4], [5, 6, ...], ...]
我经常需要做这件事情,想知道是否有比自己编写更标准的方法。在 itertools
中是否有我遗漏的内容?(可以使用 enumerate
和 groupby
来解决问题,但感觉有些笨重。)如果有人想看实现方式,这里是:
def chunk_input_stream(input_stream, chunk_size):
"""partition a generator in a streaming fashion"""
assert chunk_size >= 1
accumulator = []
for x in input_stream:
accumulator.append(x)
if len(accumulator) == chunk_size:
yield accumulator
accumulator = []
if accumulator:
yield accumulator
编辑
受kreativitea答案的启发,这里提供一个使用islice
的解决方案,它直截了当且不需要后置过滤。
from itertools import islice
def chunk_input_stream(input_stream, chunk_size):
while True:
chunk = list(islice(input_stream, chunk_size))
if chunk:
yield chunk
else:
return
# test it with list(chunk_input_stream(iter([1, 2, 3, 4]), 3))
itertools.repeat
替代[]*n
? - jpm