user5368737 user5368737 - 1 year ago 69
Python Question

Find number of consecutive elements that are the same before they change

So for example if I have the lists

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

I would want to get the longest streak of the first element in the list, so for example
would give 3,
would give 2 and
would give 1. I know I could create a while loop and count the streak that way, but I was wondering if there's a more elegant way to do this?

Answer Source

you could do something like this:

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

(this also makes sure that if all elements are like the first element, index does return the correct value)

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

from itertools import takewhile
len([tmp for tmp in takewhile(lambda x:x==a[0], a)])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download