python - 显示连续出现次数最多的数字
问题描述
如何编写一个程序来显示最并排出现的项目?
例子:
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)
解决方案
取决于您对输入的确切要求
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
。
推荐阅读
- python - 显示采样率的直方图
- r - (如何)我可以使用 av 包在 R 中合并音频文件吗?
- django - 基于 SerializerMethodField 对 django 对象进行排序
- typescript - 如何循环嵌套在 TypeScript 中的对象中的对象
- python - 制作一个包含许多元素的元组列表
- javascript - 为什么 React useEffect() 卸载不改变变量值?
- amazon-sagemaker - 我们如何在 Sagemaker 中自动执行 Jupyter notebook python 脚本?
- sql - 如何使用 LAG 函数删除我的查询结果?
- typescript - TS 路径别名未在 Webpack 5.0.0-beta.18 中使用 tsconfig-paths-webpack-plugin 解析
- mongodb - Mongodb:选择所有没有用户记录的问题并删除它