答案 0 :(得分:1)
将元组列表转换为树结构的一般方法是迭代它并创建父/子关系:
data = [(newid, parentid, name), ...] # getting the data into this format left as an excercise for the reader
# convert data into tree-structure
tree = {
newid: {
"parentid": parentid,
"name": name,
"parent": None,
"children": []
} for newid, parentid, name in data }
for newid, item in data.items():
node = tree[newid]
if node['parentid'] is not None:
parent = node['parent'] = tree[node['parentid']
parent.children.append(node)
然后你可以通过以下方式找到根节点:
roots = [node for node in tree.values() if node.parent is None]
您可以创建模板标记以帮助显示这些标记,或者您可以在javascript中执行此操作,例如如果您将roots
作为json.dumps(roots)
传递给模板:
<div id="mylst"></div>
<script>
(function drawroots(pos, roots) {
let draw_leaf = function (n) {
return '<li> + n.name + '</li>';
};
let draw_subtree = function (n) {
let res = "<li>" + n.name + "<ol>";
n.children.forEach(c => {res += draw_node(c); });
res += "</li></ol>";
};
let draw_node = function (n) {
return (node.children.length === 0) ? draw_leaf(n) : draw_subtree(n);
};
$(pos).append('<ol>');
roots.forEach(r => {
$(pos).append(draw_node(r));
});
$(pos).append('</ol>');
}('#mylst', {{roots}});
</script>
在js中有更好的方法可以做到这一点,但这应该让你开始。