如何排序字数的输出

这个问题在这里已经有了答案:

  • 如何按价值对字典进行排序? 38个答案

  • 只需使用计数器。 它将缩短您的代码并获得您想要的订购。

    从文档引用:

    Counter是用于计算可哈希对象的字典子类。 它是一个无序的集合,其元素以字典键的形式存储,并将其计数存储为字典值。 计数允许为包括零或负计数的任何整数值。 Counter类与其他语言的bag或multisets类似。

    >>> c = Counter(['eggs', 'ham'])
    >>> c['bacon']                              # count of a missing element is zero
    0
    

    您可以使用operator.itemgetter()查看排序的字典:

    from operator import itemgetter
    
    wordcount = {'test': 1, 'hello': 3, 'test2':0}
    
    sortedWords = sorted(wordcount.items(), key=itemgetter(1), reverse = True)
    

    输出:

    >>> sortedWords
    [('hello', 3), ('test', 1), ('test2', 0)]
    

    这应该为你做: -

    ally = open("alice.txt", "r")
    wordcount={}
    for word in ally.read().split():
        if word not in wordcount:
            wordcount[word] = 1
        else:
           wordcount[word] += 1
    
    for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True):
        print(k,v)
    
    链接地址: http://www.djcxy.com/p/18165.html

    上一篇: How to sort the output of a word count

    下一篇: Sorting a dictionary in python