修改了Python结构的前序树遍历

2024-06-12 11:47:00 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在尝试表示一个修改的预排序树遍历 作为一个Python结构,我可以输出到json,因为我当前的目标是在jstree中显示树

假设我有一张如图所示的桌子 http://imrannazar.com/Modified-Preorder-Tree-Traversal(在我的例子中,每一行也有一个父标识)如下所示

    Node ID   Name       Left MPTT value     Right MPTT value       ParentID
     1       (Root)             1                 16                   -1
     2       Articles           2                 11                    1
     5       Fiction            3                 8                     2
     7       Fantasy            4                 5                     5
     8       Sci-fi             6                 7                     5
     6       Reference          9                 10                    2
     3       Portfolio          12                13                    1
     4       Contact            14                15                    1

jstree的Json格式如下

^{pr2}$

如何将上表转换为Python格式 输出这个json。在

我想用一个嵌套字典 如下所示

    class NestedDict(dict):
        def __missing__(self, key):
            return self.setdefault(key, NestedDict())

我不确定我需要的算法。在

非常感谢任何帮助。在

谢谢


Tags: keyselfcomjsonhttp目标排序value
1条回答
网友
1楼 · 发布于 2024-06-12 11:47:00

你真的应该试着自己去做,展示你做了什么,哪些地方不管用。但我有几分钟的空闲时间,所以。。。在

要解析表,可以使用^{}模块。那就交给你吧。在

可能不是一个最佳解决方案,但这可以做到:

datain = (
    (1,'Root',1,16,-1),
    (2,'Articles',2,11,1),
    (5,'Fiction',3,8,2),
    (7,'Fantasy',4,5,5),
    (8,'Sci-fi',6,7,5),
    (6,'Reference',9,10,2),
    (3,'Portfolio',12,13,1),
    (4,'Contact',14,15,1),
    )

def convert_to_json(data):
    node_index = dict()
    parent_index = dict()
    for node in data:
        node_index[node[0]] = node
        parent_index.setdefault(node[4],[]).append(node)

    def process_node(index):
        result = { 'data' : node_index[index][1] }
        for node in parent_index.get(index,[]):
            result.setdefault('children',[]).append(process_node(node[0]))
        return result

    node = process_node(1)
    return [node]

退货:

^{pr2}$

相关问题 更多 >