查找list中出现次数最多的元素 发表于 2021-09-21 更新于 2022-11-24 分类于 机器学习 用三种方法来查看列表中出现次数最多的元素 ·步骤一首先将元素存入词典方法一12345678data = [1, 2, 3, 1, 3, 2, 1, 2, 2]dic = {}for i in data: if i in dic.keys(): dic[i] += 1 else: dic[i] = 1print(dic) 方法二:1234567# 方法二 data = [1, 2, 3, 1, 3, 2, 1, 2, 2]dic = {}for i in data: i = str(i) dic[i] = dic.get(i, 0) + 1print(dic) 方法三:12345import numpy as npfrom collections import Counterdata = [1, 2, 3, 1, 3, 2, 1, 2, 2]dic = Counter(data) ·步骤二:统计次数:方法一:argman函数12345678import numpy as np# 添加数据lis = []for i in dic: lis.append(dic[i]) tem = np.array(lis)print("在列表中出现最多的那个数是:",list(dic.keys())[tem.argmax()]) 方法二:argsort方法12345678import numpy as np# 添加数据lis = []for i in dic: lis.append(dic[i]) tem = np.array(lis)print("在列表中出现最多的那个数是:",list(dic.keys())[tem.argsort()[-1]]) 方法三:打擂台法12345678910lis = []for i in dic: lis.append(dic[i])diff = lis[0]for i in lis: if i > diff: diff = i inde = lis.index(i)print("在列表中出现最多的那个数是:", list(dic.keys())[inde])