Created
June 2, 2011 10:02
-
-
Save bchhun/1004199 to your computer and use it in GitHub Desktop.
Group a list into chunks in Python WITHOUT removing smaller chunks
This file contains 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
# source: http://countergram.com/python-group-iterator-list-function | |
def group_iter(iterator, n=2, strict=False): | |
""" Transforms a sequence of values into a sequence of n-tuples. | |
e.g. [1, 2, 3, 4, 5] => [(1, 2), (3, 4), (5,)] (when n == 2) | |
If strict, then it will raise ValueError if there is a group of fewer | |
than n items at the end of the sequence. """ | |
accumulator = [] | |
for item in iterator: | |
accumulator.append(item) | |
if len(accumulator) == n: # tested as fast as separate counter | |
yield tuple(accumulator) | |
accumulator = [] # tested faster than accumulator[:] = [] | |
# and tested as fast as re-using one list object | |
if strict and len(accumulator) != 0: | |
raise ValueError("Leftover values") | |
else: | |
yield tuple(accumulator) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment