怎么做按降序排序出现(在这个程序中,如果是tie /,则按字母顺序排序)

时间:2016-10-11 19:10:35

标签: python

>>> words=input('enter your sensence:')
enter your sensence:it was the best of times it was the worst of times it was the age of wisdom it was the age of foolishnes
>>> wordcount={}
>>> for word in words.split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1


>>> print(word, wordcount)
foolishnes {'age': 2, 'of': 4, 'it': 4, 'wisdom': 1, 'was': 4, 'the': 4, 'worst': 1, 'times': 2, 'foolishnes': 1, 'best': 1}

1 个答案:

答案 0 :(得分:0)

你已经有了自己的文字数量。以下是按排序顺序打印出来的方法:

def printout(wordcount):
    for k in sorted(wordcount, key=lambda k: (wordcount[k], k)):
        print(k, wordcount[k])