Skip to content

Instantly share code, notes, and snippets.

@rob-smallshire
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rob-smallshire/b02ec8b0bdd269968509 to your computer and use it in GitHub Desktop.
Save rob-smallshire/b02ec8b0bdd269968509 to your computer and use it in GitHub Desktop.
Python group_when(predicate, iterable) function
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