Last active
December 22, 2021 23:45
-
-
Save Xion/5165122 to your computer and use it in GitHub Desktop.
split() for general iterables
This file contains hidden or 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
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