-
-
Save lukmdo/1309198 to your computer and use it in GitHub Desktop.
Function to iterate over an iterable chunk by chunk, choosing the number of item of each chunks and the type of the chunk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import chain, islice | |
def chunk(seq, chunksize): | |
""" Yields items from an iterator in iterable chunks.""" | |
it = iter(seq) | |
while True: | |
yield chain([it.next()], islice(it, chunksize - 1)) | |
if __name__ == '__main__': | |
lst = ['a', 'b', 'c', 'd', 'e'] | |
for i in chunk(lst, 3): | |
print i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment