zoukankan      html  css  js  c++  java
  • 需求-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'}]}]
    

      

  • 相关阅读:
    LeetCode12: 整数转罗马数字
    LeetCode11:盛最多水的容器
    LeetCode09:判断回文数
    LeetCode08:字符串转换成整数
    LeetCode04:寻找中位数
    LeetCode03:无重复字符的最长子串
    《JAVA编程思想》第四版 PDF 下载 中文版和英文版 高清PDF扫描带书签
    XML
    异常
    委托和匿名方法和Lambda表达式
  • 原文地址:https://www.cnblogs.com/andy9468/p/9726458.html
Copyright © 2011-2022 走看看