我很惊讶我找不到将可迭代作为输入并返回可迭代的可迭代的“批处理”函数。
例如:
for i in batch(range(0,10), 1): print i
[0]
[1]
...
[9]
或者:
for i in batch(range(0,10), 3): print i
[0,1,2]
[3,4,5]
[6,7,8]
[9]
现在,我写了一个我认为非常简单的生成器:
def batch(iterable, n = 1):
current_batch = []
for item in iterable:
current_batch.append(item)
if len(current_batch) == n:
yield current_batch
current_batch = []
if current_batch:
yield current_batch
但以上并没有给我我所期望的:
for x in batch(range(0,10),3): print x
[0]
[0, 1]
[0, 1, 2]
[3]
[3, 4]
[3, 4, 5]
[6]
[6, 7]
[6, 7, 8]
[9]
所以,我错过了一些东西,这可能表明我对 python 生成器完全缺乏了解。有人愿意指出我正确的方向吗?
[编辑:我最终意识到只有当我在 ipython 而不是 python 本身中运行它时才会发生上述行为]