232121 发表于 2016-5-12 09:34:44

Python内嵌列表格式化

stackoverflow上的一个问题:
把下面的格式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[{
    "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}]




更改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    [{
      '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都是可变的.这样对于数据的深度可以简化)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
result, t = [], {}

for i in k:    # k 为上面的数据, k 建议按 parent 排序一下
    i['childs'] = []
    if i['parent'] == 'null':
      del i['parent']
      result.append(i)
      t = result
    else:
      t]['childs'].append(i)
      t] = t]['childs'][-1]
      del t]['childs'][-1]['parent']

print result




结果:

1
2
3
4
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'}]






页: [1]
查看完整版本: Python内嵌列表格式化