Created
October 1, 2020 05:29
-
-
Save kwcooper/874f6ac779f15abf58816065b3c47fac to your computer and use it in GitHub Desktop.
Group one list by another list with itertools and python 3+
This file contains 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
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