当前位置 : 主页 > 编程语言 > python >

python 父子节点生成字典

来源:互联网 收集:自由互联 发布时间:2021-06-25
lines = [(1, 1, ‘ 父1节点 ‘ ), (2, 1, ‘ 1-2 ‘ ), (3, 1, ‘ 1-3 ‘ ), (4, 3, ‘ 1-3-4 ‘ ), (5, 3, ‘ 1-3-5 ‘ ), (6, 3, ‘ 1-3-6 ‘ ), ( 7, 7, ‘ 父7节点 ‘ ), (8, 7, ‘ 7-8 ‘ ), (9, 7, ‘ 7-9 ‘ )]nodes = {}dat

 

lines = [(1, 1, 父1节点), (2, 1, 1-2), (3, 1, 1-3), (4, 3, 1-3-4), (5, 3, 1-3-5), (6, 3, 1-3-6),
     (7, 7, 父7节点), (8, 7, 7-8), (9, 7, 7-9)]

nodes = {}
data_temp =[]
for line in lines:
    id, parentId, name = line
    nodes[id] = {children: [], id: id, "parentId": parentId, "name": name, orLeafnode: 1} # orLeafnode 是叶子节点
    data_temp.append({children: [], id: id, "parentId": parentId, "name": name, orLeafnode: 1})
data = []
for i in data_temp:
    id = i[id]
    parent_id = i[parentId]
    node = nodes[id]
    if id == parent_id:
        node[orLeafnode] = 0
        data.append(node)
    else:
        parent = nodes[parent_id]
        parent[orLeafnode] = 0
        parent[children].append(node)
print(data)
参考: http://www.cocoachina.com/articles/69831
网友评论