You can use numpy:
>>> import numpy as np >>> a = [1,1,1,2,2] >>> b = [1,1,2,2,2] >>> c = [2,1,1,1,1] >>> def runs(data): ... return np.split(data, np.where(np.diff(data) != 0)[0]+1) ... >>> for e in a,b,c: ... runs(np.array(e)) ... [array([1, 1, 1]), array([2, 2])] [array([1, 1]), array([2, 2, 2])] [array([2]), array([1, 1, 1, 1])]
Then just take the length of the first run:
>>> for e in a,b,c: ... len(runs(np.array(e))[0]) ... 3 2 1
Or, in Python, just use the while :
>>> def r(a): ... i=1 ... while a[0]==a[i]: i+=1 ... return i ... >>> r(a) 3 >>> r(b) 2 >>> r(c) 1
source share