Python:找到最频繁的字节?

Vio*_*let 0 python byte frequency

我正在寻找一种(最好是简单的)方法来查找和排序python流元素中最常见的字节.

例如

>>> freq_bytes(b'hello world')
b'lohe wrd'
Run Code Online (Sandbox Code Playgroud)

甚至

>>> freq_bytes(b'hello world')
[108,111,104,101,32,119,114,100]
Run Code Online (Sandbox Code Playgroud)

我目前有一个函数返回表单中的列表list[97] == occurrences of "a".我需要对它进行排序.

我想我基本上需要翻转列表,以便list[a] = b --> list[b] = a同时删除重复.

kin*_*all 6

在集合模块中尝试Counter类.

from collections import Counter

string = "hello world"
print ''.join(char[0] for char in Counter(string).most_common())
Run Code Online (Sandbox Code Playgroud)

请注意,您需要Python 2.7或更高版本.

编辑:忘记了most_common()方法返回了一个值/计数元组列表,并使用列表推导来获取值.