Check the number of consecutive equal elements in Python

荒凉一梦 提交于 2020-02-05 04:38:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!