python返回一个列表中出现次数最多的元素

有好几种办法,由麻烦到简单慢慢来

lt = ['小马', '小敏', '小乔', '小敏', '小杜', '小杜', '小孟', '小敏']
def max_count(lt):
    # 定义一个字典,用于存放元素及出现的次数
    d = {}
    # 记录最大的次数的元素
    max_key = None
    # 遍历列表,统计每个元素出现的次数,然后保存到字典中
    for i in lt:
        if i not in d:
            # 计算元素出现的次数
            count = lt.count(i)
            # 保存到字典中
            d[i] = count
            # 记录次数最大的元素
            if count > d.get(max_key, 0):
                max_key = i
    return max_key
print(max_count(lt))

下面来个一行代码解决

# 直接统计
print(max(lt, key=lt.count))

再来一种

from collections import Counter
c = Counter(lt)
# print(dict(c))
print(c.most_common(1)[0][0])

猜你喜欢

转载自blog.csdn.net/weixin_43226574/article/details/84451090
今日推荐