Iterate an iterator by chunks (of n) in Python? -
this question has answer here:
can think of nice way (maybe itertools) split iterator chunks of given size?
therefore l=[1,2,3,4,5,6,7]
chunks(l,3)
becomes iterator [1,2,3], [4,5,6], [7]
i can think of small program not nice way maybe itertools.
the grouper()
recipe itertools
documentation's recipes comes close want:
def grouper(n, iterable, fillvalue=none): "grouper(3, 'abcdefg', 'x') --> abc def gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args)
it fill last chunk fill value, though.
a less general solution works on sequences handle last chunk desired is
[my_list[i:i + chunk_size] in range(0, len(my_list), chunk_size)]
finally, solution works on general iterators behaves desired is
def grouper(n, iterable): = iter(iterable) while true: chunk = tuple(itertools.islice(it, n)) if not chunk: return yield chunk
Comments
Post a Comment