Python:如何找到最频繁的字节?
我想找一个(最好是简单的)方法,来找出并排序在Python流元素中最常见的字节。
比如说:
>>> freq_bytes(b'hello world')
b'lohe wrd'
或者甚至:
>>> freq_bytes(b'hello world')
[108,111,104,101,32,119,114,100]
我现在有一个函数,它返回一个列表,格式是 list[97] == "a"出现的次数
。我需要把这个列表排序。
我想我基本上需要把这个列表翻转一下,也就是 list[a] = b --> list[b] = a
,同时去掉重复的项。
2 个回答
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的回答真不错!:)
6
可以试试在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()方法会返回一个包含值和计数的元组列表,然后用列表推导式来获取这些值。