Python:将列表字符串按出现频次从高到低排序并统计出现次数
Python 实现方案
collections.Counter 的 most_common() 方法不传入任何参数时,默认返回按出现频次从高到低排序的所有元素及其计数元组,可直接满足你的需求。
完整代码示例
from collections import Counter # 示例列表 winners = ['Tortoise','Tortoise','Hare'] # 获取全量降序排列的元素+计数 sorted_win_counts = Counter(winners).most_common() print(sorted_win_counts)
输出结果
[('Tortoise', 2), ('Hare', 1)]
扩展用法
- 若只需单独提取排序后的元素列表:
sorted_items = [item for item, count in sorted_win_counts] # 输出:['Tortoise', 'Hare']
- 若只需单独提取对应出现次数列表:
count_list = [count for item, count in sorted_win_counts] # 输出:[2, 1]
- 若要格式化逐行输出每个元素和对应次数:
for item, count in sorted_win_counts: print(f"{item}: 出现次数 {count}")
输出效果:
Tortoise: 出现次数 2 Hare: 出现次数 1
内容的提问来源于stack exchange,提问作者Adan
相关产品推荐
相关产品推荐

