Let’s say I have a list like below.
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
And there’s another list below treated as label
b = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,5]
I would like to make lists in a big list if the label is same like below
c = [[1,2,3], [4,5,6,7], [8,9,10,11,12], [13,14], ]
I tried if statement with append and extend, but not sure how to make it work.
itertools.groupby are the easiest tools for this IMO.
>>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] >>> b = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,5] >>> from itertools import groupby >>> [[x for x, _ in group] for _, group in groupby(zip(a, b), key=lambda t: t)] [[1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11, 12], [13, 14], ]
zip to zip the two lists together into one list of
a, b tuples,
b elements, and then use a comprehension to pull the
a elements into the final list that’s still grouped by similar