python出现次数最多_Python:列表中出现次数最多的值

如果要查找列表中每个元素的出现位置,可以使用集合中的Counter模块: –

>>> x = ['a','a','b','c','c','d']

>>> from collections import Counter

>>> count = Counter(x)

>>> count

Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1})

>>> count.most_common()

[('a', 2), ('c', 2), ('b', 1), ('d', 1)]

因此,前两个元素在您的列表中最常见.

>>> count.most_common()[0]

('a', 2)

>>> count.most_common()[1]

('c', 2)

或者,您还将参数传递给most_common()以指定您想要的最常见元素数量: –

>>> count.most_common(2)

[('a', 2), ('c', 2)]

更新: –

您还可以先查找最大计数,然后找到具有该值的元素总数,然后您可以将其用作most_common()中的参数: –

>>> freq_list = count.values()

>>> freq_list

[2, 2, 1, 1]

>>> max_cnt = max(freq_list)

>>> total = freq_list.count(max_cnt)

>>> most_common = count.most_common(total)

[('a', 2), ('c', 2)]

>>> [elem[0] for elem in most_common]

['a', 'c']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值