0

这是我的程序的一部分:

print(str(alphabet) + " ")
alphabet = OrderedDict(alphabet, key=lambda x: x[0])
print(str(alphabet) + " ")

这是该部分终端的输出:

{' ': (57301, 0.16656008557492746), 'a': (23596, 0.06858783929121637), 'c': (8761, 0.025466098492555794), 'b': (5129, 0.014908756896281095), 'e': (32343, 0.0940132431851081), 'd': (9401, 0.027326423002912572), 'g': (6125, 0.01780388691552383), 'f': (5582, 0.016225517838768), 'i': (24438, 0.0710353287251545), 'h': (10526, 0.03059652468127409), 'k': (1985, 0.005769912739153436), 'j': (622, 0.001808002883502991), 'm': (9517, 0.027663606820414736), 'l': (12504, 0.0363460901210955), 'o': (20552, 0.05973967083883195), 'n': (19586, 0.05693174353101219), 'q': (840, 0.0024416759198432674), 'p': (8986, 0.0261201188282281), 's': (20204, 0.05872811938632545), 'r': (18284, 0.053147145855255123), 'u': (7068, 0.020544958811252637), 't': (26396, 0.07672675902402726), 'w': (3767, 0.010949753797678083), 'v': (3136, 0.0091155901007482), 'y': (3600, 0.010464325370756861), 'x': (3004, 0.008731898170487114), 'z': (773, 0.0022469231976652926)} 
OrderedDict([(' ', (57301, 0.16656008557492746)), ('a', (23596, 0.06858783929121637)), ('c', (8761, 0.025466098492555794)), ('b', (5129, 0.014908756896281095)), ('e', (32343, 0.0940132431851081)), ('d', (9401, 0.027326423002912572)), ('g', (6125, 0.01780388691552383)), ('f', (5582, 0.016225517838768)), ('i', (24438, 0.0710353287251545)), ('h', (10526, 0.03059652468127409)), ('k', (1985, 0.005769912739153436)), ('j', (622, 0.001808002883502991)), ('m', (9517, 0.027663606820414736)), ('l', (12504, 0.0363460901210955)), ('o', (20552, 0.05973967083883195)), ('n', (19586, 0.05693174353101219)), ('q', (840, 0.0024416759198432674)), ('p', (8986, 0.0261201188282281)), ('s', (20204, 0.05872811938632545)), ('r', (18284, 0.053147145855255123)), ('u', (7068, 0.020544958811252637)), ('t', (26396, 0.07672675902402726)), ('w', (3767, 0.010949753797678083)), ('v', (3136, 0.0091155901007482)), ('y', (3600, 0.010464325370756861)), ('x', (3004, 0.008731898170487114)), ('z', (773, 0.0022469231976652926)), ('key', <function <lambda> at 0x1619f30>)])

如果您想知道这是计算文件中的所有字母。元组中的值是该字母出现的计数和概率。

为什么要添加'('key', at 0x1619f30>)'?

4

2 回答 2

1

您是否试图确保您的字典具有按字母顺序排列的键?如果是这样,您需要在第一次对它们进行排序后一次将它们插入 OrderedDict 中。下面的代码将做到这一点。

# Extract keys from dictionary into list and sort them
keys = list(alphabet).sort()

# Now insert them into the new ordered dictionary.
d = OrderedDict() 
for k in keys:
    d[k] = alphabet[k]

如果你有 Python 2.7+,你可以使用字典理解并一举完成整个事情:

d = {k: alphabet[k] for k in list(alphabet).sort()}
于 2013-11-16T19:24:51.493 回答
1

OrderedDict 不接受任何特殊key参数,因此该参数只是作为普通键添加到 dict 中。

但是,从您的代码的外观来看,我猜您对 OrderedDict 有更根本的误解。你读过文档吗?

有序字典就像普通字典一样,但它们记住插入项目的顺序

注意我强调的。OrderedDict 中的“有序”并不意味着“排序”。这些项目不会以任何方式相互比较。它只记住它们添加的顺序。

于 2013-11-16T19:24:55.357 回答