Python如何统计不同数字

Python如何统计不同数字

作者:William Gu发布时间:2026-01-05阅读时长:0 分钟阅读次数:17

用户关注问题

Q
如何用Python统计列表中各数字出现的次数?

我有一个数字列表,想知道每个数字出现了多少次,有什么简便的方法可以实现吗?

A

使用collections模块的Counter统计数字出现次数

Python的collections模块中提供了Counter类,非常适合统计列表中元素的频率。你可以直接将数字列表传入Counter,它会返回一个字典,键是数字,值是对应的出现次数。例如:

from collections import Counter
numbers = [1,2,2,3,3,3,4]
cnt = Counter(numbers)
print(cnt)
Q
怎样用Python找出列表中出现频率最高的数字?

我想知道列表中哪个数字出现得最多,应该怎么做?

A

利用Counter的most_common方法找出最高频数字

Counter对象有一个most_common方法,可以返回出现次数最多的元素及次数。使用方法如下:

from collections import Counter
numbers = [1,2,2,3,3,3,4]
cnt = Counter(numbers)
most_common_num = cnt.most_common(1)[0]
print(f'数字{most_common_num[0]}出现了{most_common_num[1]}次')
Q
如何统计数字出现次数并按次数排序?

想按数字出现次数排序显示,可以怎么实现?

A

将Counter结果转换列表并根据频率排序

Counter对象本身是无序的,需要转换成列表然后排序。可以这样操作:

from collections import Counter
numbers = [1,2,2,3,3,3,4]
cnt = Counter(numbers)
sorted_items = sorted(cnt.items(), key=lambda x: x[1], reverse=True)
print(sorted_items)