码迷,mamicode.com
首页 > 其他好文 > 详细

需求-shidebing

时间:2018-09-29 21:33:52      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:int()   pre   根据   dict   and   构建   列表   ict   set   

# 原始数据
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‘}]}]

  

需求-shidebing

标签:int()   pre   根据   dict   and   构建   列表   ict   set   

原文地址:https://www.cnblogs.com/andy9468/p/9726458.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!