Skip to content

Instantly share code, notes, and snippets.

@Xion
Last active December 22, 2021 23:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xion/5165122 to your computer and use it in GitHub Desktop.
Save Xion/5165122 to your computer and use it in GitHub Desktop.
split() for general iterables
import inspect
def split(iterable, by):
"""Generalized split function that works on any iterable."""
separator = by if inspect.isfunction(by) else lambda x: x == by
res = []
curr = []
for elem in iterable:
if separator(elem):
res.append(curr)
curr = None
else:
curr = curr or []
curr.append(elem)
res.append([] if curr is None else curr)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment