获取数组中数量最多的元素,也就是最频繁的那个元素,方法有很多,下面是3种最简单的:
用max函数
sample = [1,2,3,3,3,4,5,5]
max(set(sample), key=sample.count)
用collections包的Counter函数
from collections import Counter
sample = [1,2,3,3,3,4,5,5]
data = Counter(sample)
data.most_common(1)[0][0]
# data.most_common(1)[0][1] # 就是相应的最高频元素的频次
用statistics包的mode函数
from statistics import mode
mode(sample)
>>> a = [1,1,1,1,2,2,2,2,3,3,3,1,1,2,3,1,3,1,3,1,3,1,2,3,1,3]
>>> a
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 1, 1, 2, 3, 1, 3, 1, 3, 1, 3, 1, 2, 3, 1, 3]
>>> set(a)
{1, 2, 3}
>>> a.count(1)
11
参考:https://www.cnblogs.com/arkenstone/p/6838812.html