[英]Python: find most frequent bytes?
我正在尋找一種(最好是簡單的)方法來查找和排序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
同時刪除重復項。
在collections模塊中嘗試Counter類 。
from collections import Counter
string = "hello world"
print ''.join(char[0] for char in Counter(string).most_common())
請注意,您需要Python 2.7或更高版本。
編輯:忘記了most_common()方法返回值/計數元組的列表,並使用列表推導來獲取值。
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的答案很糟糕。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.