如何找到列表中出现最频繁的元素?

53

给定以下列表

['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 
 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 
 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 
 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 
 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 
 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 
 'Moon', 'to', 'rise.', '']

我想要统计每个单词出现的次数,并显示前三个。

然而,我只希望找到首字母大写的前三个单词,并忽略所有首字母不大写的单词。

我相信还有更好的方法,但我的想法是:

  1. 将列表中的第一个单词放入另一个名为uniquewords的列表中
  2. 删除原始列表中第一个单词及其重复项
  3. 将新的第一个单词添加到unique words中
  4. 从原始列表中删除第一个单词及其重复项
  5. 等等...
  6. 直到原始列表为空为止...
  7. 计算uniquewords中每个单词在原始列表中出现的次数
  8. 找到前三个并打印

1
这不是另一个问题的副本,因为其他问题上的一些解决方案(statistics.mode)无法解决此问题。 - user202729
11个回答

1
如果您正在使用Count,或者已经创建了自己的Count-style字典并且想要显示项目的名称和计数,您可以像这样遍历字典:
top_10_words = Counter(my_long_list_of_words)
# Iterate around the dictionary
for word in top_10_words:
        # print the word
        print word[0]
        # print the count
        print word[1]

或者在模板中迭代这个内容:
{% for word in top_10_words %}
        <p>Word: {{ word.0 }}</p>
        <p>Count: {{ word.1 }}</p>
{% endfor %}

希望这能帮助到某人。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接