SHARE
TWEET

chunker for iterables

DeaD_EyE Oct 31st, 2018 24 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def chunker(iterable, chunksize, return_type=tuple):
  2.     '''
  3.    A generator, which yields chunks with given chunksize
  4.    as return_type tuple.
  5.  
  6.    iterable := any object which is iterable
  7.    chunksize := chunksize of each chunk
  8.    return_type := returns the chunks as given type.
  9.  
  10.    example:
  11.        >>> a = list(chunker(range(100), 10))
  12.        >>> print(a)
  13.    '''
  14.     def get_chunk():
  15.         for n, element in enumerate(iterator, start=1):
  16.             yield element
  17.             if n == chunksize:
  18.                 break
  19.     iterator = iter(iterable)
  20.     while True:
  21.         chunk = return_type(get_chunk())
  22.         if not chunk:
  23.             break
  24.         yield chunk
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top