我不知道如何排序的字母列表及其升序即{'z':1, 'g':3, 'a':5, and so on}
频率
我试图重新Huffman算法,无损压缩算法,在Python。 txt
是文本字符串,这是已经分手了这么每个字母,包括空格,是一个单独的索引。我一直在使用Counter(txt)
,其中发现每个字母有多少次出现在txt
并创建一个字典尝试。但这个订单最高频率到最低频率的字典,我需要它是反之亦然,所以它遵循霍夫曼算法的步骤。然后我尝试添加
for key, value in sorted(freq.iteritems(), key=lambda(k,v): (v,k)):
print("%s: %s" % (key, value))
然而,这将创建一个语法错误,我不知道这是做的最好的方式。
这里是我的代码:
from collections import Counter
def huffman(file):
txt = list(map(lambda c2: c2, file)) # Places each individual char into array.
freq=Counter(txt) #Counts numb of times a letter appears.
print(freq)
for key, value in sorted(freq.iteritems(), key=lambda(k,v): (v,k)):
print("%s: %s" % (key, value))
我只是需要freq
字典是为了从最常见最普通的,这样它遵循霍夫曼的算法的步骤。因此,而不是{'a':5, 'g':3, 'z':1}
是{'z':1, 'g':3, 'a':5}
在Python版本3.6或以下,使用:
from collections import OrderedDict
freq = OrderedDict(sorted(freq.items(), key=lambda x: x[1]))
从Python版本3.7开始,您可以使用此:
freq = dict(sorted(freq.items(), key=lambda x: x[1]))
从3.7版本及以上dictonary Dictonary开始被默认排序。每个元组的拳头元素是字母和第二元件是它的频率。所以,在排序的功能,我们使用的每个元素的频率为重点,以增加序进行排序。
如果你真的想要一个有序字典背你必须通过一对夫妇箍跳:)
你会想那种字典首批获得一个平坦的列表:
import operator
a = {'a':5, 'g':3, 'z':1}
sorted_list = sorted(a.items(), key=operator.itemgetter(1))
然后,你会传递到OrderedDict:
from collections import OrderedDict
ordered_dict = OrderedDict(sorted_list)
ordered_dict:
OrderedDict([('z', 1), ('g', 3), ('a', 5)])
然后,你可以索引这样:
ordered_dict['z']
输出:
1