Python:通过循环添加子节点

时间:2017-11-25 14:25:34

标签: python python-2.7 kivy kivy-language

如何通过循环添加子节点?我正在使用treeView。我已经定义了行数组。在此Primary1中,Primary2,Primary3是父节点。和Primary1的Secpndary1子节点。 r [1]定义主要或次要,r [2]定义父节点名称

rows = [('Primary1', 'Primary', None), ('Primary2', 'Primary', None),
        ('Secpndary1', 'Secondary', 'Primary1'),('Primary3', 'Primary', None)]


tree = []

for r in rows:
    tree.append({'node_id': r[1], 'children': []})

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

rows = [('Primary1', 'Primary', None), ('Primary2', 'Primary', None),
    ('Secpndary1', 'Secondary', 'Primary1'),('Primary3', 'Primary', None)]


tree = []

for r in rows:
    if r[2] is None:
        tree.append({'node_id': r[0], 'children': []})
for r in rows:
    if r[2] is not None:
        for node in tree:
            if node['node_id'] == r[2]:
                node['children'].append({'node_id': r[0], 'children': []})

答案 1 :(得分:0)

这是另一种可行的解决方案。

rows = [('Primary1', 'Primary', None), ('Primary2', 'Primary', None),
        ('Secpndary1', 'Secondary', 'Primary1'),('Primary3', 'Primary', None), ('Secondary2', 'Secondary', 'Primary1')]

from collections import defaultdict
dd = defaultdict(list)
for row in rows:
    node , _ , child = row
    x = dd[child].append(node) if child else dd[node]

print dd

>>> dd
defaultdict(<type 'list'>, {'Primary2': [], 'Primary3': [], 'Primary1': ['Secpndary1', 'Secondary2']})