【问题标题】:How to print the first ten elements from Counter in python如何在python中从Counter打印前十个元素
【发布时间】:2017-10-11 15:37:36
【问题描述】:

使用此代码,我首先打印所有按文本文件中最常用单词排序的元素。但是我如何打印前十个元素?

with open("something.txt") as f:
    words = Counter(f.read().split())
print(words)

【问题讨论】:

    标签: python counter


    【解决方案1】:

    来自文档:

    最常见的([n])

    返回 n 个最常见元素的列表及其从最常见到最少的计数。如果 n 被省略或没有,most_common() 返回计数器中的所有元素。数量相等的元素任意排序:

    我会尝试:

    words = Counter(f.read().split()).most_common(10)
    

    来源:here

    【讨论】:

      【解决方案2】:

      这将在您的words Counter 中为您提供most common 十个字:

      first_ten_words = [word for word,cnt in words.most_common(10)]
      

      您只需要从(word, count) 返回的对列表中提取第一个元素Counter.most_common()

      >>> words.most_common(10)
      [('qui', 4),
       ('quia', 4),
       ('ut', 3),
       ('eum', 2),
       ('aut', 2),
       ('vel', 2),
       ('sed', 2),
       ('et', 2),
       ('voluptas', 2),
       ('enim', 2)]
      

      使用简单的列表理解:

      >>> [word for word,cnt in words.most_common(10)]
      ['qui', 'quia', 'ut', 'eum', 'aut', 'vel', 'sed', 'et', 'voluptas', 'enim']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多