How do I process the elements of a sequence in batches, idiomatically?
For example, with the sequence \"abcdef\" and a batch size of 2, I would like to do something
Here is a solution, which yields a series of iterators, each of which iterates over n items.
def groupiter(thing, n):
def countiter(nextthing, thingiter, n):
yield nextthing
for _ in range(n - 1):
try:
nextitem = next(thingiter)
except StopIteration:
return
yield nextitem
thingiter = iter(thing)
while True:
try:
nextthing = next(thingiter)
except StopIteration:
return
yield countiter(nextthing, thingiter, n)
I use it as follows:
table = list(range(250))
for group in groupiter(table, 16):
print(' '.join('0x{:02X},'.format(x) for x in group))
Note that it can handle the length of the object not being a multiple of n.