Created
June 12, 2025 15:16
-
-
Save phrz/a70b0c2e4b2eea74ce5faa14931c7159 to your computer and use it in GitHub Desktop.
Splits lists on separator elements with custom comparator function
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
def chunk_on(l, sep, test=lambda a, b: a == b, include_sep=False, skip_empty=True): | |
'''for list `l`, yield slices that represent each run of the list between `sep`s.''' | |
start = 0 | |
end = 0 | |
for i in range(len(l)): | |
if test(l[i], sep): | |
end = i | |
if include_sep and i < len(l) - 1: | |
end += 1 | |
if (skip_empty and start != end) or not skip_empty: | |
yield l[start:end] | |
start = end + 1 | |
if l[-1] != sep: | |
yield l[start:] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment