如何统计无序列表中元素的频率?

289 投票
33 回答
700470 浏览
提问于 2025-04-15 18:38

假设你有一串乱七八糟的数字,比如:

a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]

我想知道每个数字在这个列表里出现了多少次,像这样:

# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output

33 个回答

118

Python 2.7及以上版本引入了字典推导式。这种方法可以通过列表来创建字典,这样不仅能统计数量,还能去掉重复的项。

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> d = {x:a.count(x) for x in a}
>>> d
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
>>> a, b = d.keys(), d.values()
>>> a
[1, 2, 3, 4, 5]
>>> b
[4, 4, 2, 1, 2]
644

在Python 2.7(或者更新的版本)中,你可以使用collections.Counter这个工具:

>>> import collections
>>> a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
>>> counter = collections.Counter(a)
>>> counter
Counter({1: 4, 2: 4, 5: 2, 3: 2, 4: 1})
>>> counter.values()
dict_values([2, 4, 4, 1, 2])
>>> counter.keys()
dict_keys([5, 1, 2, 4, 3])
>>> counter.most_common(3)
[(1, 4), (2, 4), (5, 2)]
>>> dict(counter)
{5: 2, 1: 4, 2: 4, 4: 1, 3: 2}
>>> # Get the counts in order matching the original specification,
>>> # by iterating over keys in sorted order
>>> [counter[x] for x in sorted(counter.keys())]
[4, 4, 2, 1, 2]

如果你在用Python 2.6或者更早的版本,你可以在这里下载一个实现。

172

如果这个列表是排好序的,你可以使用来自 itertools 这个标准库里的 groupby 函数(如果没有排好序,你可以先把它排序,不过这样会花费 O(n lg n) 的时间):

from itertools import groupby

a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
[len(list(group)) for key, group in groupby(sorted(a))]

输出结果:

[4, 4, 2, 1, 2]

撰写回答