python返回一个列表中出现次数最多的元素
一个最简单的方法:
lst = [‘小李’, ‘小张’, ‘小王’, ‘小张’, ‘小杜’, ‘小杜’, ‘小袁’, ‘小张’]
print(max(lst, key=lst .count))
python 返回一个列表中出现次数最多的元素
def max_list(lt):
temp = 0
for i in lt:
if lt.count(i) > temp:
max_str = i
temp = lt.count(i)
return max_str
n = [1,2,2,2,3,3,3,3,4,4]
print(max_list(n))
下面是随便写的:
lst = [‘小李’, ‘小张’, ‘小王’, ‘小张’, ‘小杜’, ‘小杜’, ‘小杜’, ‘小袁’, ‘小张’]
lst2 = set()
dicts = {}
tsum = 0
k52=0
for i in set(lst):
dicts[i] = 0
dictsed = dicts
for i1 in lst:
for i2 in dicts.keys():
if i1 == i2:
dictsed[i2] = dictsed.get(i2) + 1
dictsedsum = {}
for k, j in dictsed.items():
if j >= tsum:
tsum = j
dictsedsum.clear()
dictsedsum[k] = j
for i in dictsedsum.values():
k52=i
disuccess={}
for k1, j1 in dictsed.items():
if j1 == k52:
disuccess[k1]=j1
print(disuccess)
方法2
listNum = [2, 2, ‘a’, ‘a’, ‘b’, ‘b’, ‘c’, 1, 1, ‘’, ‘’]
intNum = 0
dictA = {}
dictB = {}
for iA in listNum:
if iA in dictA.keys():
dictA[iA] = dictA.get(iA) + 1
if dictA.get(iA) > intNum:
intNum = dictA.get(iA)
else:
dictA[iA] = 1
for k, j in dictA.items():
if intNum == j:
dictB[k] = j
print(dictB)
方法3、
nb = [5,‘a’,‘a’,‘b’,‘b’,1,3,’’,’’]
intNum=0
dictB={}
for i in nb:
if nb.count(i)>=intNum:
intNum=nb.count(i)
for i1 in nb:
if nb.count(i1)==intNum:
dictB[i1]=intNum
print(dictB)
方法4、
n = [1, 1, 2, 2, 3]
dictns = {}
na = max(n, key=n.count)
inum = n.count(na)
for i in n:
if n.count(i) == inum:
dictns[i] = inum
print(dictns)