Last active
December 13, 2023 02:48
-
-
Save nathan-cruz77/97efd4856dfafc4359b032fa65148af3 to your computer and use it in GitHub Desktop.
Group consecutive equal items of iterable
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
# Group equal consecutive items of iterable. | |
# | |
# | |
# Sample usage: | |
# | |
# >>> group_equal('aaabbcd') | |
# [['a', 'a', 'a'], ['b', 'b'], ['c'], ['d']] | |
# | |
def group_equal(iterable): | |
subgroups = [] | |
g = [] | |
for item in iterable: | |
if not g or item == g[0]: | |
g.append(item) | |
else: | |
subgroups.append(g) | |
g = [item] | |
if g: | |
subgroups.append(g) | |
return subgroups |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment