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

Python如何将Counter统计的字典值累加至键1-99的全0目标字典

实现方案

核心逻辑

不需要提前将字典的键、值转为列表,直接遍历Counter返回的dict1的键值对,先做键存在性校验,再累加值即可,代码非常简洁。

完整可运行代码

from collections import Counter
arr = [2,2,2,2,2,2,4,4,4,4,6,6,6,6,7,7,7,7,8,8,8]
dict1 = Counter(arr)
# 预初始化dict2,1-99的键初始值为0
dict2 = dict.fromkeys(range(1,100), 0)

# 核心累加逻辑
for key, count in dict1.items():
    # 校验键存在于dict2中,避免1-99范围外的非法键引发报错
    if key in dict2:
        dict2[key] += count

# 结果验证示例
print(dict2[2]) # 输出6
print(dict2[4]) # 输出4

补充说明

  • 如果你能保证待统计的数组里只有1-99的整数,完全可以省略key in dict2的校验逻辑,直接累加即可,不会触发KeyError
  • 你现有代码里生成的val_list、values_list属于无效代码,可以直接删除,不需要做额外的类型转换

内容的提问来源于stack exchange,提问作者MadCodex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:36:01