How to find Run length encoding in python

前端 未结 3 1902
梦毁少年i
梦毁少年i 2021-01-18 06:42

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 same numbers like:

 values: 2, 1, 2, 3
l         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 07:07

    You can do this 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)]
    

提交回复
热议问题