Find the number of consecutive elements that will be the same until they change

So for example, if I have lists

a = [1,1,1,2,2] b = [1,1,2,2,2] c = [2,1,1,1,1] 

I would like to get the longest line of the first element in the list, so for example, a will give 3, b will give 2 and c will give 1. I know that I can create a loop for a while and calculate the strip this way, but I was interested Is there a more elegant way to do this?

+5
source share
4 answers

you can do something like this:

 numStreak = ([a[0] == n for n in a]+[False]).index(False) 

(this also ensures that if all elements are similar to the first element, the index returns the correct value)

UPDATE: a more efficient (but less elegant?) Version

 from itertools import takewhile len([1 for _ in takewhile(lambda x:x==a[0], a)]) 

or a little better (UPDATE 2) @vaultah suggestion:

 sum(1 for _ in takewhile(lambda x:x==a[0], a)) 
+6
source

You can use groupby and summarize the number of elements in the first group for each:

 a = [1,1,1,2,2] b = [1,1,2,2,2] c = [2,1,1,1,1] from itertools import groupby for l in [a,b,c]: print(sum( 1 for _ in next(groupby(l), [[], []],)[1])) 

Or using takewhile:

 from itertools import takewhile for l in [a, b, c]: print(sum((1 for _ in takewhile(lambda x: x == l[0], l)))) 

If your data is always a list, a tuple, etc. in a group, you can check the value of falsity, and not set the default value in next(.. :

 for l in [a, b, c]: print(sum(1 for _ in next(groupby(l))[1]) if l else 0) 
+3
source

One liner for the road? Take the sight ...

 a = [5,5,5,5,8] list(np.ediff1d(a)).count(0)+1 >>> 4 
+1
source

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 
0
source

All Articles