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))
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With