Finding the number of equal elements at the beginning of a list
Given a list in python, I would like to know how many equal elements are at the beginning of the list.
Input example:
x1 = ['a','a','b','c','a','a','a','c']
x2 = [1, 1, 1, 3, 1, 1, 1, 8]
x3 = ['foo','bar','foobar']
Some magic function (or one liner) will appear:
f(x1) = 2 # There are 2 'a' values in the beginning.
f(x2) = 3 # There are 3 1-values in the beginning.
f(x3) = 1 # Only 1 'foo' in beginning.
If I do this:
sum([1 if x=='a' else 0 for x in x1])
I just get the number of occurrences of "a" in x1, not the number of leading values ββper string. It would be nice to have one liner that doesn't have to know the first meaning.
+3
source to share
3 answers
itertools.groupby
may I help...
from itertools import groupby
def f(lst):
if_empty = ('ignored_key', ())
k, v = next(groupby(lst), if_empty)
return sum(1 for _ in v)
And of course we can turn that into a 1-liner (no import):
sum(1 for _ in next(groupby(lst), ('ignored', ()))[1])
But I would not recommend it.
demo:
>>> from itertools import groupby
>>>
>>> def f(lst):
... if_empty = ('ignored_key', ())
... k, v = next(groupby(lst), if_empty)
... return sum(1 for _ in v)
...
>>> f(x1)
2
>>> f(x2)
3
>>> f(x3)
1
>>> f([])
0
+5
source to share
It might be better to check for the first occurrence of something that is not equal to the first value:
x1 = ['a','a','b','c','a','a','a','c']
x2 = [1, 1, 1, 3, 1, 1, 1, 8]
x3 = ['foo','bar','foobar']
x4 = []
x5 = [1,1,1,1,1,1]
def f(x):
pos = -1
for pos,a in enumerate(x):
if a!=x[0]:
return pos
return pos+1
print(f(x1))
print(f(x2))
print(f(x3))
print(f(x4))
print(f(x5))
2
3
1
0
6
+1
source to share