且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查Python中连续相等元素的数量

更新时间:2023-11-29 09:08:34

使用 groupby 方法:

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}]