import itertools from functools import partial def window(sequence, window_size, uncomplete=True, fillvalue=None): if uncomplete: izip = partial(itertools.zip_longest, fillvalue=fillvalue) else: izip = zip yield from izip(*[iter(sequence)] * window_size)
l = list(range(10)) for chunk in window(l, 3): print(chunk)
Output:(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, None, None)
If you use uncomplete=False
, the zip function will be used.The zip function stops iterating, if there are not enough values, to fill the window.
l = list(range(10)) for chunk in window(l, 3, uncomplete=False): print(chunk)
Output:(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!