Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 显示一行中出现次数最多的数字_Python_Python 3.x_Algorithm_List - Fatal编程技术网

Python 显示一行中出现次数最多的数字

Python 显示一行中出现次数最多的数字,python,python-3.x,algorithm,list,Python,Python 3.x,Algorithm,List,如何编写一个程序,向我显示最并排出现的项目 例如: 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

如何编写一个程序,向我显示最并排出现的项目

例如:

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是最常见的,因为它是同一个项目中最长的未间断的延伸,那么你可以用相同的值选择Max Lin:

如果您对最常出现在其旁边的元素感兴趣,可以压缩列表以获取相邻项目对,过滤相同的项目对,将它们传递给,并获取最常见的项目:


对于您的6164466示例,两者都将返回4。

您能展示一下您到目前为止尝试了什么吗?这是:您最喜欢并排的意思是什么?一批?什么是最并行的1 1 2 2 1 1 1 1?tobias_k the 4 2如果你想要没有任何库的东西,你可以通过一个简单的循环和一些计数变量来实现。类似于……的东西。可能只是更容易使用groupby或Counter,如下所示。
lst = [1, 1, 1, 2, 2, 2, 2, 1, 1, 1]
max((len(list(g)), k) for k, g in itertools.groupby(lst))
# (4, 2)  # meaning 2 appeared 4 times
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