本文介绍了检查Python中连续相等元素的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目的是确定给定字符串或列表中连续相等元素的最大数量.
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,'a','a',1)-> {1:2,'a':2}
(1,1,'a','a',1) ->{1:2, 'a':2}
(2,2,2,0,2,2,0)-> {2:3,0:1}
(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
推荐答案
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)
结果:
[{0: 1}, {2: 3}]
这篇关于检查Python中连续相等元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!