如何找到列表中最常见的元素? [英] How to find most common elements of a list?

查看:58
本文介绍了如何找到列表中最常见的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供以下列表

['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.', '']

我试图计算每个单词出现的次数并显示前3个.

I am trying to count how many times each word appears and display the top 3.

但是,我只想查找首字母大写的前三位,而忽略所有首字母大写的单词.

However I am only looking to find the top three that have the first letter capitalized and ignore all words that do not have the first letter capitalized.

我敢肯定有比这更好的方法,但是我的想法是做以下事情:

I am sure there is a better way than this, but my idea was to do the following:

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

推荐答案

如果您使用的是Python的早期版本,或者您有充分的理由推出自己的单词计数器(我想听听!),您可以使用dict尝试以下方法.

If you are using an earlier version of Python or you have a very good reason to roll your own word counter (I'd like to hear it!), you could try the following approach using a dict.

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> word_list = ['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.', '']
>>> word_counter = {}
>>> for word in word_list:
...     if word in word_counter:
...         word_counter[word] += 1
...     else:
...         word_counter[word] = 1
... 
>>> popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
>>> 
>>> top_3 = popular_words[:3]
>>> 
>>> top_3
['Jellicle', 'Cats', 'and']

最重要的提示:只要您想使用这种算法,交互式Python解释器就是您的朋友.只需键入它,然后观察它,然后检查整个过程中的元素即可.

Top Tip: The interactive Python interpretor is your friend whenever you want to play with an algorithm like this. Just type it in and watch it go, inspecting elements along the way.

这篇关于如何找到列表中最常见的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆