如何统计列表中所有数字的出现次数并按频次从高到低排序?
按数字出现次数排序并统计的实现方案
方法一:使用collections.Counter(推荐)
Counter是Python标准库中专门用于统计元素出现次数的工具,能直接完成计数并支持按次数排序。
假设你的空格分隔数字数据是字符串形式(比如输入1 1 1 2 2 3),可以这样处理:
from collections import Counter # 读取空格分隔的数字字符串,转换为整数列表 data_str = input("请输入空格分隔的数字:") num_list = list(map(int, data_str.split())) # 统计每个数字的出现次数 counts = Counter(num_list) # 按出现次数从多到少排序,次数相同则按数字本身升序排序(可选) sorted_counts = sorted(counts.items(), key=lambda x: (-x[1], x[0])) # 按要求格式输出 for num, count in sorted_counts: print(f"{num}:{count}x")
运行后输入1 1 1 2 2 3,输出为:
1:3x 2:2x 3:1x
方法二:不使用标准库(手动实现)
如果不想依赖Counter,可以手动遍历列表统计次数:
data_str = input("请输入空格分隔的数字:") num_list = list(map(int, data_str.split())) count_dict = {} # 手动统计每个数字的出现次数 for num in num_list: if num in count_dict: count_dict[num] += 1 else: count_dict[num] = 1 # 按出现次数降序排序 sorted_counts = sorted(count_dict.items(), key=lambda x: (-x[1], x[0])) # 输出结果 for num, count in sorted_counts: print(f"{num}:{count}x")
关键说明
split()方法会自动将空格分隔的字符串拆分为列表,无需手动添加逗号;- 排序时
lambda x: (-x[1], x[0])中,-x[1]实现按次数降序排列,x[0]保证次数相同时数字从小到大排序(可按需调整); - 两种方法都支持任意数量的数字输入,无需逐个指定要统计的数字。
内容的提问来源于stack exchange,提问作者G-J GAMES
相关产品推荐
相关产品推荐

