### 如何将分层列表排序为dicts的树/嘧啶模型？

``````hierarchy =
array([[[ 7, -1,  1, -1],
[-1, -1,  2,  0],
[-1, -1,  3,  1],
[-1, -1,  4,  2],
[-1, -1,  5,  3],
[ 6, -1, -1,  4],
[-1,  5, -1,  4],
[ 8,  0, -1, -1],
[-1,  7, -1, -1]]])
``````

``````{0:{1:{2:{3:{4:{5:{},6:{}}}}}},
7:{},
8:{}}
``````

#### 2 个答案:

``````import numpy as np
H = np.array(
[[ 7, -1,  1, -1],
[-1, -1,  2,  0],
[-1, -1,  3,  1],
[-1, -1,  4,  2],
[-1, -1,  5,  3],
[ 6, -1, -1,  4],
[-1,  5, -1,  4],
[ 8,  0, -1, -1],
[-1,  7, -1, -1]])

def T(i):
children = [(h, j) for j, h in enumerate(H) if h[3] == i]
children.sort(key = lambda h: h[0][1])
return {c[1]: T(c[1]) for c in children}

print T(-1)
``````

``````{0: {1: {2: {3: {4: {5: {}, 6: {}}}}}}, 8: {}, 7: {}}
``````

``````T = lambda i: {j: T(j) for j, h in enumerate(H) if h[3] == i}
print T(-1)
``````

``````def make_hdict(hier):
def recur(parent):
res = {}
for i,n in enumerate(hier):
if n[3] == parent:
res[i] = recur(i)
return res
return recur(-1)
``````

``````hierarchy = [[ 7, -1,  1, -1], #0
[-1, -1,  2,  0], #1
[-1, -1,  3,  1], #2
[-1, -1,  4,  2], #3
[-1, -1,  5,  3], #4
[ 6, -1, -1,  4], #5
[-1,  5, -1,  4], #6
[ 8,  0, -1, -1], #7
[-1,  7, -1, -1]] #8
print(make_hdict(hierarchy))
=> {0: {1: {2: {3: {4: {5: {}, 6: {}}}}}}, 8: {}, 7: {}}
``````

1. 我没有使用＆＃34;下一个兄弟＆＃34;和以前的兄弟姐妹＆＃34;因为字典是无序的
2. 我没有使用＆＃34;第一个孩子＆＃34;因为它是多余的信息。
3. 这就是你想要的吗？