Last active
August 29, 2015 14:04
-
-
Save rob-smallshire/b02ec8b0bdd269968509 to your computer and use it in GitHub Desktop.
Python group_when(predicate, iterable) function
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
def group_when(pred, iterable): | |
"""Yield groups (as lists), starting a new group when pred(item) is True. | |
The predicate is ignored for the first item in iterable, which always starts | |
a new group. | |
Args: | |
pred: A predicate function used to determine when a new group | |
should be started. | |
iterable: Any iterable series of objects which can be passed to pred(). | |
Yields: | |
Lists of grouped items in the same order as from iterable. | |
""" | |
iterator = iter(iterable) | |
try: | |
group = [next(iterator)] | |
except StopIteration: | |
return | |
for item in iterator: | |
if pred(item): | |
yield group | |
group = [] | |
group.append(item) | |
if group: | |
yield group |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment