我是编码新手,并且陷入了尝试对元组列表进行递归排序的过程中。这是我的代码:
# table consists on [(code, parent), (code, parent), ...]
table = [('1', ''),
('1.1', '1'),
('2', ''),
('2.1','2'),
('2.1.1','2.1'),
('3',''),
('3.1','3'),
('4',''),
('4.1','4'),
('4.1.1','4.1'),
('4.1.2','4.1')]
content = {}
def rec(table, parent=None):
while True:
try:
_code = table[0][0]
_parent = table [0][1]
if _parent == '':
content[_code] = _parent
return rec(table[1:])
else:
if _parent in content:
if content[_parent] == '':
content[_parent] = table[0]
else:
content[_parent] = content[_parent], table[0]
return rec(table[1:], parent=_parent)
else:
content[_parent] = table[0]
return rec(table[1:], parent=_parent)
except IndexError:
break
return content
print(rec(table))
我得到的输出:
{'1': ('1.1', '1'), '2': ('2.1', '2'), '2.1': ('2.1.1', '2.1'), '3':('3.1', '3'), '4': ('4.1', '4'), '4.1': (('4.1.1', '4.1'), ('4.1.2','4.1'))}
但所需的输出将是:
{'1': ('1.1', '1'), '2': ('2.1', '2'), {'2.1': ('2.1.1', '2.1')}, '3': ('3.1','3'), '4': ('4.1', '4'), {'4.1': ('4.1.1', '4.1'), ('4.1.2', '4.1')}
我需要类似的东西:
{'node_id': '1', 'name':'somename', 'children': [{'node_id': '1.1' ,'name':'somename', 'children': [{'node_id': '1.1.1', 'name':'somename', 'children': [{'node_id': '1.1.1.1', 'name':'somename', 'children': []}]}, {'node_id': '1.1.2', 'name':'somename', 'children': []}, {'node_id': '1.1.3', 'name':'somename', 'children': []}]}, {'node_id': '1.2', 'name':'somename', 'children': []}]}
关于如何实现我的目标有什么想法吗?