【发布时间】:2016-11-12 14:27:20
【问题描述】:
我正在编写一个如下所示的小程序
"""Count words."""
# TODO: Count the number of occurences of each word in s
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
# TODO: Return the top n words as a list of tuples (<word>, <count>)
from operator import itemgetter
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
t1=[]
t2=[]
temp={}
top_n={}
words=s.split()
for word in words:
if word not in temp:
t1.append(word)
temp[word]=1
else:
temp[word]+=1
t1 = sorted(temp,key=temp.get,reverse=True) # to get sorted keys
t2 = sorted(temp.values(),reverse=True) # to get sorted values
top_n = dict(zip(t1,t2))
print top_n
return
def test_run():
"""Test count_words() with some inputs."""
count_words("cat bat mat cat bat cat", 3)
count_words("betty bought a bit of butter but the butter was bitter", 3)
if __name__ == '__main__':
test_run()
我只是想对键值对进行排序。我有以下问题:
- 在上面的程序中,当我打印两个排序列表的合并时,它只显示未排序的合并
- 如何通过 python 函数获取排序的键值对,我正在使用的当前 fxn 返回键或值。我们能以某种方式得到两者吗?
【问题讨论】:
-
你查看collections.Counter了吗?您也可以考虑 collections.defaultdict 摆脱您的 if 语句。
defaultdict(0)将创建一个字典,它使用 0 作为未知键的默认值。
标签: python sorting keyvaluepair