Skip to content

Instantly share code, notes, and snippets.

@seanpianka
Last active June 19, 2022 06:33
Show Gist options
  • Save seanpianka/1e65b89e5e09f245a07f4d668cb3a44c to your computer and use it in GitHub Desktop.
Save seanpianka/1e65b89e5e09f245a07f4d668cb3a44c to your computer and use it in GitHub Desktop.
Python: create sublist by condition (Split a Python list into a list of lists where the lists are split around elements matching a certain criteria)
from itertools import islice, zip_longest
def yield_subgroups(group, subgroup_test):
subgroup = []
for i, j in zip_longest(group, islice(group, 1, None)):
if subgroup_test(i, j):
yield subgroup
subgroup = []
else:
subgroup.append(i)
yield subgroup
num_list = [97, 122, 99, "", 98, 111, 112, "", 113, 100, 102]
res = list(yield_subgroups(num_list, lambda i, j: i == ""))
print(res) # [[97, 122, 99], [98, 111, 112], [113, 100, 102]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment