【发布时间】:2014-03-06 09:12:15
【问题描述】:
我想对一个特定的字典进行排序并返回 top_n 出现次数的列表。字典是 txt 文档中单词的集合,“key”是 txt 文件中的单个单词,“value”是它在文档中出现的次数。
我的init方法如下:
def __init__(self:'Collection_of_words', file_name: str) -> None:
''' this initializer will read in the words from the file,
and store them in self.counts'''
l_words = open(file_name).read().split()
s_words = set(l_words)
self.counts = dict([ [word, l_words.count(word)]
for word
in s_words])
现在,我的一个实例方法将返回一个字符串列表,该列表的出现次数为“前 n”,给出了一些 int 参数。我试了一下:
def top_n_words(self, i):
'''takes one additional parameter, an int,
<i> which is the top number of occurences. Returns a list of the top <i> words.'''
return [ pair[0]
for pair
in sorted(associations, key=lambda pair: pair[1], reverse=True)[:5]]
但是,每当我运行此代码时,我都会遇到错误并且无法弄清楚原因。我不确定如何对字典对象进行排序(例如 self.counts)
【问题讨论】:
-
你只是需要这个来工作,还是你想找出方法来作为一个学习练习?有一个内置类可以更有效地为您执行此操作,
collections.Counter。 -
不,我试图在没有 collections.Counter 帮助的情况下将此作为学习练习。
标签: python list sorting python-3.x dictionary