获取List中出现次数最多的那个数

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

方法一

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)

方法二:

# 方法二 
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)

方法三:

import numpy as np
from collections import Counter

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

·步骤二:统计次数:

方法一:argman函数

import numpy as np
# 添加数据
lis = []
for i in dic:
    lis.append(dic[i])
    
tem = np.array(lis)
print("在列表中出现最多的那个数是:",list(dic.keys())[tem.argmax()])

方法二:argsort方法

import numpy as np
# 添加数据
lis = []
for i in dic:
    lis.append(dic[i])
    
tem = np.array(lis)
print("在列表中出现最多的那个数是:",list(dic.keys())[tem.argsort()[-1]])

方法三:打擂台法

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])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值