首页 > 解决方案 > 显示连续出现次数最多的数字

问题描述

如何编写一个程序来显示最并排出现的项目?

例子:

6 1 6 4 4 4 6 6

我想要四个,而不是六个,因为总共只有两个六。

这是我尝试过的(来自评论):

c = int(input())
h = [] 
for c in range(c):
    h.append(int(input()))
final = []
n = 0    
for x in range(c-1):
    c = x
    if h[x] == h[x+1]:
        n+=1
        while h[x] != h[c]:
            n+=1
        final.append([h[c],n])
print(final)        

标签: pythonpython-3.xalgorithmlist

解决方案


取决于您对输入的确切要求

lst = [1, 1, 1, 2, 2, 2, 2, 1, 1, 1]

如果您认为这四个2是最常见的,因为它是相同项目最长的不间断延伸,那么您可以groupby使用相同的值并选择一个max len

max((len(list(g)), k) for k, g in itertools.groupby(lst))
# (4, 2)  # meaning 2 appeared 4 times

如果您对最常出现在其旁边的元素感兴趣,您可以zip列表获取相邻项目对,过滤相同的项目,通过 a 传递它们Counter,并获得most_common

collections.Counter((x,y) for (x,y) in zip(lst, lst[1:]) if x == y).most_common(1)
# [((1, 1), 4)]  # meaning (1,1) appeared 4 times

对于您的示例6 1 6 4 4 4 6 6,两者都将返回4


推荐阅读