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

如何在不导入工具函数的情况下按num和e1分组newlist数据?

作业任务:嵌套字典转换实现

要求不导入任何工具函数,将给定的newlist列表转换为以num为主键、e1为次级键的嵌套字典结构,最终结构形式为:{ num: {e1: [ {'num':..., 'e1': ..., 'e2': ... }, ... ], ...}, ... },其中单条数据对应列表仅含一个元素。

原始data数据

data = [
    ['num','e1','e2','e3'],
    ['2002','p','r','i'],
    ['2002','k','r','i'],
    ['2001','k','r','e'],
    ['2004','p','a','p'],
    ['2004','p','s','f']
]

待转换的newlist

newlist = [
    {'num': '2001', 'e1': 'k', 'e2': 'r', 'e3': 'e'},
    {'num': '2002', 'e1': 'p', 'e2': 'r', 'e3': 'i'},
    {'num': '2002', 'e1': 'k', 'e2': 'r', 'e3': 'i'},
    {'num': '2004', 'e1': 'p', 'e2': 'a', 'e3': 'p'},
    {'num': '2004', 'e1': 'p', 'e2': 's', 'e3': 'f'}
]

目标结构

{
    '2001':{
        'k':[{'num': '2001', 'e1': 'k', 'e2': 'r', 'e3': 'e'}]
    },
    '2002':{
        'k':[{'num': '2002', 'e1': 'k', 'e2': 'r', 'e3': 'i'}],
        'p':[{'num': '2002', 'e1': 'p', 'e2': 'r', 'e3': 'i'}]
    },
    '2004':{
        'p':[{'num': '2004', 'e1': 'p', 'e2': 'a', 'e3': 'p'}, {'num': '2004', 'e1': 'p', 'e2': 's', 'e3': 'f'}]
    }
}

实现代码

# 初始化空字典存储结果
result = {}

for item in newlist:
    num_key = item['num']
    e1_key = item['e1']
    
    # 若num键不存在,创建对应空字典
    if num_key not in result:
        result[num_key] = {}
    # 若e1键不存在,创建对应空列表
    if e1_key not in result[num_key]:
        result[num_key][e1_key] = []
    # 将当前项添加到对应列表
    result[num_key][e1_key].append(item)

# 打印验证结果
import pprint
pprint.pprint(result)

实现逻辑

  1. 创建空字典result用于存储最终结构
  2. 遍历newlist的每一项:
    • 提取当前项的num和e1作为层级键
    • 逐级检查键是否存在,不存在则创建对应空容器(字典或列表)
    • 将当前字典项追加到对应层级的列表中
  3. 最终result即为符合要求的嵌套字典

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:53:07