江东的笔记

Be overcome difficulties is victory

0%

查找list中出现次数最多的元素

用三种方法来查看列表中出现次数最多的元素

·步骤一首先将元素存入词典

方法一

1
2
3
4
5
6
7
8
data = [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] = 1
print(dic)

方法二:

1
2
3
4
5
6
7
# 方法二 
data = [1, 2, 3, 1, 3, 2, 1, 2, 2]
dic = {}
for i in data:
i = str(i)
dic[i] = dic.get(i, 0) + 1
print(dic)

方法三:

1
2
3
4
5
import numpy as np
from collections import Counter

data = [1, 2, 3, 1, 3, 2, 1, 2, 2]
dic = Counter(data)

·步骤二:统计次数:

方法一:argman函数

1
2
3
4
5
6
7
8
import numpy as np
# 添加数据
lis = []
for i in dic:
lis.append(dic[i])

tem = np.array(lis)
print("在列表中出现最多的那个数是:",list(dic.keys())[tem.argmax()])

方法二:argsort方法

1
2
3
4
5
6
7
8
import numpy as np
# 添加数据
lis = []
for i in dic:
lis.append(dic[i])

tem = np.array(lis)
print("在列表中出现最多的那个数是:",list(dic.keys())[tem.argsort()[-1]])

方法三:打擂台法

1
2
3
4
5
6
7
8
9
10
lis = []
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])