Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all groups in a list in python?

Tags:

python

list

I have a list like this

[0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1] 

and I want to group them and then find the length of each group. So the result will be like that:

[[2,0],[3,1].....[4,1]]
like image 914
IordanouGiannis Avatar asked Dec 28 '22 13:12

IordanouGiannis


1 Answers

Use itertools.groupby:

>>> import itertools
>>> l =  [0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1]
>>> [(len(list(g)), k) for k,g in itertools.groupby(l)]
[(2, 0), (3, 1), (3, 0), (2, 1), (2, 0), (4, 1)]
like image 97
Mark Byers Avatar answered Jan 10 '23 12:01

Mark Byers