0

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

例如

>>> freq_bytes(b'hello world')
b'lohe wrd'

甚至

>>> freq_bytes(b'hello world')
[108,111,104,101,32,119,114,100]

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

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

4

2 回答 2

6

尝试集合模块中的Counter 类

from collections import Counter

string = "hello world"
print ''.join(char[0] for char in Counter(string).most_common())

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

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

于 2010-09-09T01:51:05.053 回答
3
def frequent_bytes(aStr):
    d = {}
    for char in aStr:
        d[char] = d.setdefault(char, 0) + 1

    myList = []
    for char, frequency in d.items():
        myList.append((frequency, char))
    myList.sort(reverse=True)

    return ''.join(myList)

>>> frequent_bytes('hello world')
'lowrhed '

我只是尝试了一些明显的东西。不过,@kindall 的回答很震撼。:)

于 2010-09-09T01:52:45.740 回答