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

Python如何将元组列表转换为按年月分组的指定格式字典列表

现有代码的问题
  • 变量引用错误:循环遍历写的是for a,b,c,d in se,但原始数据变量名为data,代码运行会直接触发NameError。
  • 输出结构不匹配:你以(月份, 年份)元组作为defaultdict的键,最终得到的是键为年月元组、值为统计字典的二级字典结构,不是目标要求的字典列表;同时打印时会带出defaultdict的类型标识,不符合纯数据结构的要求。
  • 键名不符合预期:直接将完整的证书类型字符串(如base-certificate)作为字典键,没有处理成目标要求的短键名base/case/standard。
  • 缺少结果转换步骤:分组完成后没有将分组容器里的值提取为列表,无法得到目标的数组结构。
最优实现方案

核心逻辑还是按年月维度分组,只需要修正键名处理、补上结果转换步骤即可,以下是两种常用实现:

方案1:基于defaultdict的修正写法(和你原有思路一致)

from collections import defaultdict

raw_data = [
    ('base-certificate', 60, 3, 2022), 
    ('case-certificate', 1, 3, 2022), 
    ('standard-certificate', 7, 3, 2022),
    ('base-certificate', 50, 4, 2022), 
    ('case-certificate', 80, 4, 2022), 
    ('standard-certificate', 10, 4, 2022)
]

group_dict = defaultdict(dict)
for cert_full_name, val, month, year in raw_data:
    # 截取证书类型短键名
    cert_key = cert_full_name.replace('-certificate', '')
    time_key = (month, year)
    # 初始化当前年月的x字段
    if 'x' not in group_dict[time_key]:
        group_dict[time_key]['x'] = [month, year]
    group_dict[time_key][cert_key] = val

# 提取所有分组的值,转为列表即为最终结果
result = list(group_dict.values())

运行输出完全匹配预期结构:

[{'x': [3, 2022], 'base': 60, 'case': 1, 'standard': 7}, {'x': [4, 2022], 'base': 50, 'case': 80, 'standard': 10}]

方案2:无额外依赖的原生Python写法

不需要导入collections库,适合轻量场景:

raw_data = [
    ('base-certificate', 60, 3, 2022), 
    ('case-certificate', 1, 3, 2022), 
    ('standard-certificate', 7, 3, 2022),
    ('base-certificate', 50, 4, 2022), 
    ('case-certificate', 80, 4, 2022), 
    ('standard-certificate', 10, 4, 2022)
]

group_dict = {}
for cert_full_name, val, month, year in raw_data:
    cert_key = cert_full_name.removesuffix('-certificate')  # Python3.9+可用,低版本替换为replace写法
    time_key = (month, year)
    if time_key not in group_dict:
        group_dict[time_key] = {'x': [month, year]}
    group_dict[time_key][cert_key] = val

result = list(group_dict.values())

说明:Python3.7及以上版本的原生字典默认保留插入顺序,最终结果里的年月顺序和原始数据中首次出现的顺序一致;如果使用更低版本Python,需要保证顺序的话可以将group_dict替换为collections.OrderedDict实例。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:54:06