问题
My purpose is to determine the maximum number of consecutive equal elements in a given string or list.
I'll try to be more clear using an example:
(1,1,1,1) -> {1:4}
(1,1,'a','a',1) ->{1:2, 'a':2}
(2,2,2,0,2,2,0) -> {2:3, 0:1}
I have tired with something like that but it does not work:
d={}
for i in range(len(l)):
while l[i]==l[i+1]:
d[i]=l.count(i)
return d
回答1:
One possible approach, using itertools.groupby:
from itertools import groupby
t = 1,1,'a','a',1
out = {}
for v, g in groupby(t):
l = sum(1 for _ in g)
if out.get(v, float('-inf')) < l:
out[v] = l
print(out)
Prints:
{1: 2, 'a': 2}
回答2:
Another solution here, using itertools' groupby method:
from itertools import groupby
l = [2,2,2,0,2,2,0]
elems = list(set(l))
g = [{elem : max([len(list(g)) for k,g in groupby(l) if elem == k])} for elem in elems]
print(g)
Result:
[{0: 1}, {2: 3}]
来源:https://stackoverflow.com/questions/59921262/check-the-number-of-consecutive-equal-elements-in-python