You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从小时数据列表生成统计各元素出现次数的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 02:54:02