stackoverflow上的一个问题:
把下面的格式:
[{ "id": 1, "title": "node1", "parent": "null"},{ "id": 2, "title": "node2", "parent": 1},{ "id": 3, "title": "node3", "parent": 1},{ "id": 4, "title": "node4", "parent": 2},{ "id": 5, "title": "node5", "parent": 2}]
更改为:
[{ ‘id‘:1, ‘title‘:‘node1‘, ‘childs‘:[ { ‘id‘:2, ‘title‘:‘node2‘ ‘childs‘:[ { ‘id‘:4, ‘title‘:‘node4‘, ‘childs‘: [] }, { ‘id‘:5, ‘title‘:‘node5‘, ‘childs‘: [] } ] }, { ‘id‘:3, ‘title‘:‘node3‘ ‘childs‘:[] } ] }]
相关代码:(主要用了python对象的可变性,如dict,list都是可变的.这样对于数据的深度可以简化)
result, t = [], {} for i in k: # k 为上面的数据, k 建议按 parent 排序一下 i[‘childs‘] = [] if i[‘parent‘] == ‘null‘: del i[‘parent‘] result.append(i) t[1] = result[0] else: t[i[‘parent‘]][‘childs‘].append(i) t[i[‘id‘]] = t[i[‘parent‘]][‘childs‘][-1] del t[i[‘parent‘]][‘childs‘][-1][‘parent‘] print result
结果:
Z:\DOWNLOAD>k.py [{‘childs‘: [{‘childs‘: [{‘childs‘: [], ‘id‘: 4, ‘title‘: ‘node4‘}, {‘childs‘: [ ], ‘id‘: 5, ‘title‘: ‘node5‘}], ‘id‘: 2, ‘title‘: ‘node2‘}, {‘childs‘: [], ‘id‘: 3, ‘title‘: ‘node3‘}], ‘id‘: 1, ‘title‘: ‘node1‘}]
时间: 2024-10-19 20:43:46