gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:53 24 4
gpt4 key购买 nike

我有一个包含 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)]

关于python - 如何在 python 中获取列表中出现频率最高的 10 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10099602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com