python 树形结构生成
生成数据
list_data = [
{'id': 1, 'name': '体育0', 'pid': 0},
{'id': 2, 'name': '体育1', 'pid': 1},
{'id': 3, 'name': '体育2', 'pid': 1},
{'id': 4, 'name': '体育3', 'pid': 2},
{'id': 5, 'name': '体育4', 'pid': 2},
{'id': 6, 'name': '体育5', 'pid': 5},
{'id': 7, 'name': '体育6', 'pid': 5},
{'id': 8, 'name': '体育7', 'pid': 5},
{'id': 8, 'name': '体育7', 'pid': 11},
]
json_tree = [
{
"id": 1,
"name": "\u4f53\u80b20",
"pid": 0,
"children": [
{
"id": 2,
"name": "\u4f53\u80b21",
"pid": 1,
"children": [
{
"id": 4,
"name": "\u4f53\u80b23",
"pid": 2,
"children": []
},
{
"id": 5,
"name": "\u4f53\u80b24",
"pid": 2,
"children": [
{
"id": 6,
"name": "\u4f53\u80b25",
"pid": 5,
"children": []
},
{
"id": 7,
"name": "\u4f53\u80b26",
"pid": 5,
"children": []
},
{
"id": 8,
"name": "\u4f53\u80b27",
"pid": 5,
"children": []
}
]
}
]
},
{
"id": 3,
"name": "\u4f53\u80b22",
"pid": 1,
"children": []
}
]
}
]
def get_list(pid):
data = []
for x in list_data:
if x['pid'] == pid:
next_pid = x['id']
x['children'] = get_list(next_pid)
data.append(x)
return data
def traversal_tree(path, pid):
for index, item in enumerate(path):
if len(item['children']) > 0:
print('parent pid:', pid, '', item['id'])
return traversal_tree(item['children'], item['id'])
else:
print('pid:', pid, '', item['id'])
if __name__ == '__main__':
traversal_tree(json_tree, 0)
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/17124301.html