• 需求-shidebing


    # 原始数据
    list1 = [
        {"c_id": "101", "e_code": "201"},
        {"c_id": "102", "e_code": "202"},
        {"c_id": "103", "e_code": "201"},
        {"c_id": "104", "e_code": "204"},
        {"c_id": "105", "e_code": "204"},
    ]
    # 变形后的目标数据
    list2 = [
        {'201':
             [{"c_id": "101", "e_code": "201"},
              {"c_id": "103", "e_code": "201"}, ]
         },
        {'202':
             [{"c_id": "102", "e_code": "202"}, ]
         },
        {"204":
             [{"c_id": "104", "e_code": "204"},
              {"c_id": "105", "e_code": "204"}, ]
         }
    ]
    
    e_code_val_list = []
    new_data = []
    # 遍历原始数据list1,获取e_code的值列表
    for dict_new in list1:
        # print()
        for k, v in dict_new.items():
            # print("%s=%s" % (k, v))
            if k == "e_code":
                e_code_val_list.append(v)
    
    print("=========0==========")
    # "e_code"值去重
    e_code_val_list = list(set(e_code_val_list))
    print(e_code_val_list)
    
    print("=========1==========")
    # 根据e_code的值分类,遍历原始数据list1,
    for val in e_code_val_list:
        new_data.append({val: []})
    print(new_data)
    
    print("=========2==========")
    # 构建目标数据
    for dict_new in new_data:
        # print(dict)
        for k_e_c, v_list in dict_new.items():
            # print(k_e_c)
            for dict_old in list1:
                # print(dict)
                for k, v in dict_old.items():
                    if k == "e_code" and v == k_e_c:
                        dict_new[k_e_c].append(dict_old)
    
    print(new_data)
    

      

    输出:

    =========0==========
    ['204', '201', '202']
    =========1==========
    [{'204': []}, {'201': []}, {'202': []}]
    =========2==========
    [{'204': [{'c_id': '104', 'e_code': '204'}, {'c_id': '105', 'e_code': '204'}]}, {'201': [{'c_id': '101', 'e_code': '201'}, {'c_id': '103', 'e_code': '201'}]}, {'202': [{'c_id': '102', 'e_code': '202'}]}]
    

      

  • 相关阅读:
    Python __str__() 方法
    vim快捷键大全
    Python @函数装饰器及用法
    ImportError: No module named typing报错
    centos7安装pycharm2018专业版及破解
    windows下使用pycharm开发基于ansible api的python程序
    一个Windows系统下同时安装Python2和Python3
    django models def __str__(self)
    django model中的class Meta
    nmap命令详解
  • 原文地址:https://www.cnblogs.com/andy9468/p/9726458.html
Copyright © 2020-2023  润新知