Skip to content

Instantly share code, notes, and snippets.

@mumuxme
Last active December 8, 2017 10:21
Show Gist options
  • Select an option

  • Save mumuxme/cc40ad6da61dae4bac304ac5af25064a to your computer and use it in GitHub Desktop.

Select an option

Save mumuxme/cc40ad6da61dae4bac304ac5af25064a to your computer and use it in GitHub Desktop.
Python itertools
from itertools import zip_longest
def splitby(xs, f):
"""Split a list by a function.
>>> splitby([{'a': 1}, {'b': 2}, {'a': 3}], lambda x: x.get('a'))
[[{'a': 1}, {'b': 2}], [{'a': 3}]]
>>> splitby([1, 0, 0, 1, 0], lambda x: x == 1)
[[1, 0, 0], [1, 0]]
"""
index = [i for i, v in enumerate(map(lambda x: True if f(x) else False, xs)) if v]
return [xs[start:stop] for start, stop in zip_longest(index, index[1:])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment