Skip to content

Instantly share code, notes, and snippets.

@kwcooper
Created October 1, 2020 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwcooper/874f6ac779f15abf58816065b3c47fac to your computer and use it in GitHub Desktop.
Save kwcooper/874f6ac779f15abf58816065b3c47fac to your computer and use it in GitHub Desktop.
Group one list by another list with itertools and python 3+
from itertools import groupby
l1 = [1,1,1,2,2,2,2,2,1,1,1,0,0,0]
l2 = range(len(l1))
[(k, list(group)) for k, group in groupby(l2, key=lambda _, ig=iter(l1): next(ig))]
# Returns [(1, [0, 1, 2]), (2, [3, 4, 5, 6, 7]), (1, [8, 9, 10]), (0, [11, 12, 13])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment