如何在python中获取列表中10个最频繁的字符串

2024-05-29 02:10:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有93个不同字符串的列表。我需要找到10个最频繁的字符串,返回的顺序必须是从最频繁到最不频繁。

mylist = ['"and', '"beware', '`twas', 'all', 'all', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'arms', 'as', 'as', 'awhile', 'back', 'bandersnatch', 'beamish', 'beware', 'bird', 'bite', 'blade', 'borogoves', 'borogoves', 'boy', 'brillig']
 # this is just a sample of the actual list.

我没有最新版本的python,不能使用计数器。


Tags: and字符串列表顺序asbackallarms
3条回答

不使用Counter作为问题请求的修改版本

已更改为使用@Duncan建议的heap.nlargest

>>> from collections import defaultdict
>>> from operator import itemgetter
>>> from heapq import nlargest
>>> mylist = ['"and', '"beware', '`twas', 'all', 'all', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'arms', 'as', 'as', 'awhile', 'back', 'bandersnatch', 'beamish', 'beware', 'bird', 'bite', 'blade', 'borogoves', 'borogoves', 'boy', 'brillig']
>>> c = defaultdict(int)
>>> for item in mylist:
        c[item] += 1


>>> [word for word,freq in nlargest(10,c.iteritems(),key=itemgetter(1))]
['and', 'all', 'as', 'borogoves', 'boy', 'blade', 'bandersnatch', 'beware', 'bite', 'arms']

David的答案是最好的——但是如果您使用的Python版本不包括collections模块(在Python 2.7中引入)中的Counter,那么您可以使用做相同事情的Counter类的this implementation。我怀疑它会比模块慢,但会做同样的事情。

您可以使用^{} module中的^{}来执行此操作。

from collections import Counter
c = Counter(mylist)

然后执行c.most_common(10)返回

[('and', 13),
 ('all', 2),
 ('as', 2),
 ('borogoves', 2),
 ('boy', 1),
 ('blade', 1),
 ('bandersnatch', 1),
 ('beware', 1),
 ('bite', 1),
 ('arms', 1)]

相关问题 更多 >

    热门问题