【发布时间】:2012-10-25 17:32:02
【问题描述】:
我想分块输入流以进行批处理。给定一个输入列表或生成器,
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))
【问题讨论】:
标签: python stream itertools chunking