Skip to main content
 首页 » 编程设计

python之如何在 python 中获取列表中出现频率最高的 10 个字符串

2025年05月04日19kevingrace

我有一个包含 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,无法使用计数器。

请您参考如下方法:

你可以使用 Counter来自 collections 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)]