python - 如何计算无序列表中元素的频率?

标签 python list frequency

给定一个无序列表的值,例如

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

最佳答案

在 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 或更早版本,您可以下载一个实现 here .

关于python - 如何计算无序列表中元素的频率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161752/

相关文章:

java - 我在网上找到的一个有趣的谷歌面试算法,需要线性时间

java - 音频信号调制产生变声效果

python - 倒谱法的基频

c# - 如何从列表下限到上限中选择项目?

c# - 如何验证模拟对象是否已从模拟列表中删除?

通过全局公共(public) IP 地址连接的 Python 套接字

python - Cython 和 gcc : can't run compiled program

c# - SharePoint GetListItems - 获取所有列,按集列表 ID 过滤。 C#

python - 在路由之前修改 flask url

python - Jinja 在渲染后保留模板标签