#以下是网上的一个牛人给你的解决方法
from collections import Counter
a=['bj', 'bj', 'bj', 'gz', 'shh', 'shh']
d=Counter(a)
print d
print d.most_common()
print d.most_common()[0]
from collections import Counter
a=['bj', 'bj', 'bj', 'gz', 'shh', 'shh']
d=Counter(a)
print d
print d.most_common()
print d.most_common()[0]
print d.most_common()[0][0]
方法二:
一个网友的写法:
def sortbylistcount(self,list):
cnt=0
city=""
for x in list:
if list.count(x)>cnt:
city=x
cnt=list.count(x)
return city
方法三:
for n in a:
old=a.count(n)
num=max(a.count(m) for m in a)
if num==old:
print n
break
本文介绍了三种不同的方法来找出列表中最常出现的元素。第一种方法使用了Python的collections模块中的Counter类来快速统计元素频率并找出最常见的元素;第二种方法通过遍历列表并计算每个元素的出现次数来确定最频繁的元素;第三种方法则直接对比每个元素的计数,以找出最大计数值对应的元素。
9408

被折叠的 条评论
为什么被折叠?



