算法 - Python如何将数据库导出的数据一级级分类?

查看:77
本文介绍了算法 - Python如何将数据库导出的数据一级级分类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

lst = [{'time': '2016-10-25', 'id': 'a1', 'type': '1', 'details': 'xxx'},
       {'time': '2016-10-25', 'id': 'a1', 'type': '1', 'details': 'xxx'},
       {'time': '2016-10-25', 'id': 'a2', 'type': '1', 'details': 'xxx'},
       {'time': '2016-10-25', 'id': 'a2', 'type': '2', 'details': 'xxx'},
       {'time': '2016-10-26', 'id': 'a1', 'type': '1', 'details': 'xxx'},
       {'time': '2016-10-26', 'id': 'a1', 'type': '2', 'details': 'xxx'},
       {'time': '2016-10-26', 'id': 'a2', 'type': '1', 'details': 'xxx'},
       {'time': '2016-10-26', 'id': 'a2', 'type': '2', 'details': 'xxx'},
       {'time': '2016-10-27', 'id': 'a1', 'type': '1', 'details': 'xxx'},
       {'time': '2016-10-27', 'id': 'a1', 'type': '1', 'details': 'xxx'},
       {'time': '2016-10-27', 'id': 'a2', 'type': '2', 'details': 'xxx'},
       {'time': '2016-10-27', 'id': 'a2', 'type': '2', 'details': 'xxx'},
       {'time': '2016-10-27', 'id': 'a2', 'type': '3', 'details': 'xxx'},
       {'time': '2016-10-27', 'id': 'a2', 'type': '3', 'details': 'xxx'}]

结果:

lst = [{'time': '2016-10-25', 'data': [{'id': 'a1', 'data': [{'type': '1', 'data': [{'details': 'xxx'}, {'details': 'xxx'}]}]},
                                       {'id': 'a2', 'data': [{'type': '1', 'data': [{'details': 'xxx'}]},
                                                             {'type': '2', 'data': [{'details': 'xxx'}]}]}]},
       {'time': '2016-10-26', 'data': [{'id': 'a1', 'data': [{'type': '1', 'data': [{'details': 'xxx'}]},
                                                             {'type': '2', 'data': [{'details': 'xxx'}]}]},
                                       {'id': 'a2', 'data': [{'type': '1', 'data': [{'details': 'xxx'}]},
                                                             {'type': '2', 'data': [{'details': 'xxx'}]}]}]},
       {'time': '2016-10-27', 'data': [{'id': 'a1', 'data': [{'type': '1', 'data': [{'details': 'xxx'}, {'details': 'xxx'}]}]},
                                       {'id': 'a2', 'data': [{'type': '2', 'data': [{'details': 'xxx'}, {'details': 'xxx'}]},
                                                             {'type': '3', 'data': [{'details': 'xxx'}, {'details': 'xxx'}]}]}]}]

就是对列表中的数据进行一级级分类,原始数据是随机的,先按time分类,后面按id,然后type分类,每一级的数据都放在data的下,data是一个列表

真实的数据量比较大,怎么高效写这段程序?Python代码,谢谢

解决方案

import itertools

def group_by(l, key, data_callback):
    return [{key: k, 'data': data_callback(g)} for k, g in itertools.groupby(l, key=lambda x: x[key])]
    
groupby(lst, 'time',
    lambda l: group_by(l, 'id',
        lambda l: group_by(l, 'type',
            lambda l: [{'details': x['details']} for x in l])))

这篇关于算法 - Python如何将数据库导出的数据一级级分类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆