如何从小时数据列表生成统计各元素出现次数的dictionary
实现方法
两种常用实现方案如下:
方案1:使用Python标准库collections.Counter(最简便)
from collections import Counter # 你现有的小时列表 hour_list = ['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10', '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16'] # 统计每个小时出现次数,得到键值对字典 count_dict = dict(Counter(hour_list)) # 按小时升序排序后输出指定格式 for hour in sorted(count_dict.keys()): print(f"{hour} {count_dict[hour]}")
方案2:手动实现统计(无需导入额外库)
如果不想依赖任何导入模块,可以手动遍历计数:
hour_list = ['09', '18', '16', '15', '15', '14', '11', '11', '11', '11', '11', '11', '10', '10', '10', '09', '07', '06', '04', '04', '04', '19', '17', '17', '16', '16', '16'] count_dict = {} for hour in hour_list: if hour in count_dict: count_dict[hour] += 1 else: count_dict[hour] = 1 # 排序输出 for hour in sorted(count_dict.keys()): print(f"{hour} {count_dict[hour]}")
两种方案运行后都会输出你需要的格式结果,其中count_dict就是你要的键值对字典。
内容的提问来源于stack exchange,提问作者Bungy Cord
相关产品推荐
相关产品推荐

