如何从python中的列表中获取最常见的元素

Dim*_*tha 2 python list python-3.x

我有一个如此处所示的列表. a=[1936,2401,2916,4761,9216,9216,9604,9801] 我想获得更多重复的值.在这里它是'9216'我怎么能得到这个值?谢谢

Tot*_*tem 7

你可以使用collections.Counter这个:

from collections import Counter

a = [1936, 2401, 2916, 4761, 9216, 9216, 9604, 9801] 

c = Counter(a)

print(c.most_common(1)) # the one most common element... 2 would mean the 2 most common
[(9216, 2)] # a set containing the element, and it's count in 'a'
Run Code Online (Sandbox Code Playgroud)

来自文档:

在此输入图像描述 在此输入图像描述