How to find encoding of run length in python

I have an array ar = [2,2,2,1,1,2,2,3,3,3,3]

. For this array, I want to find the lengths of consecutive identical numbers, for example:

 values: 2, 1, 2, 3
lengths: 3, 2, 2, 4

      

This R

is obtained using a function rle()

. Is there any existing function in python that provides the required output?

+3


source to share


1 answer


You can do it with groupby



In [60]: from itertools import groupby
In [61]: ar = [2,2,2,1,1,2,2,3,3,3,3]
In [62]: print [(k, sum(1 for i in g)) for k,g in groupby(ar)]
[(2, 3), (1, 2), (2, 2), (3, 4)]

      

+9


source







All Articles