×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Python
Posted by: Ivan Shpotenko
Added: Jul 31, 2017 9:11 AM
Views: 10
gist: https://github.com/IvanShpotenko/chunks
Each yilded chunk is a generator of size n.
That means you have to empty (iterate over) current chunk in order to get the right result.
Last chunk will be sized as is and will not be padded with any value.

for chunk in chunks(range(25), n=7):
print(list(chunk))
>>> [0, 1, 2, 3, 4, 5, 6]
>>> [7, 8, 9, 10, 11, 12, 13]
>>> [14, 15, 16, 17, 18, 19, 20]
>>> [21, 22, 23, 24]
  1. from itertools import islice, chain
  2.  
  3.  
  4. def chunks(iterable: iter, n: int) -> iter:
  5.     '''
  6.    Generator that yields successive n-sized chunks from an iterable.
  7.    Each yilded chunk is a generator of size=chunk_size ().
  8.    That means you have to empty (iterate over) current chunk in order to get the right result
  9.    Last chunk will be sized as is and will not be padded with any value.
  10.    ABCDEFGH -> ABC, DEF, GH
  11.    >>> for chunk in chunks(range(25), n=7):
  12.    ...     print(list(chunk))
  13.    [0, 1, 2, 3, 4, 5, 6]
  14.    [7, 8, 9, 10, 11, 12, 13]
  15.    [14, 15, 16, 17, 18, 19, 20]
  16.    [21, 22, 23, 24]
  17.    '''
  18.     iterator = iter(iterable)
  19.     for first in iterator:
  20.         yield chain([first], islice(iterator, n - 1))
  21.  
  22. if __name__ == "__main__":
  23.     import doctest
  24.     doctest.testmod(verbose=True)