找出一个列表中出现次数最多的元素

在实现knn算法中遇到的问题,如何从一个列表中找出出现次数最多元素,方法是:字典 + 字典get方法统计次数 + 字典排序找出最大。

num_list = np.random.randint(0,10,100, np.int)
num_dict = {}
    
# 统计每个元素出现的次数
for i in range(len(number)):
    num_dict[num_list[i]] = num_dict.get(num_list[i], 0) + 1
                
# 排序, 找出出现次数最多的数
mostTimes_num = sorted(num_dict.items(), key=lambda x: x[1], reverse=True)[0][0]




你可能感兴趣的:(Python,Python)