Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count how many times values has appeared continuously in array python?

I have an array of elements x=[9,2,2,2,2,3,4,4,55,55,6,2,2,2,7,0,0], I would like to know how many times a value has shown continuously in this array, using python language. The expected results should be: a=[1,4,1,2,2,1,3,1,2]

The below code shows the duplicated number in x

x=[9,2,2,2,2,3,4,4,55,55,6,2,2,2,7,0,0]
def times_so_far(ls):
    out = [0]*len(ls)
    for i in range(len(ls)):
        out[i] = ls[:i].count(ls[i]) 
    return out
print(times_so_far(x))
like image 757
skysky2000 Avatar asked Dec 24 '22 03:12

skysky2000


1 Answers

You can use itertools.groupby:

from itertools import groupby
x=[9,2,2,2,2,3,4,4,55,55,6,2,2,2,7,0,0]
out = [len([*group]) for i, group in groupby(x)]
>>> out
[1, 4, 1, 2, 2, 1, 3, 1, 2]
like image 177
sacuL Avatar answered Dec 28 '22 09:12

sacuL