python - 将平面数据转换为分层 python 列表

标签 python hierarchical

我的数据库中有一个数据模型。这是一个按左值排序的扁平 Python 列表。

>     id    name        left    right
>     1 Beginning   1   6
>     2 FOO     2   5
>     3 BAR     3   4
>     4 Programming 6   13
>     5 Python      7   8
>     7 C#      9   12
>     8 XNA     10  11
>     6 About       14  15

我想将其计算成一个分层的 python 列表,然后将其转换为 HTML/XML 作为无序列表。 Python 列表是列表中的列表。

例子

categories = [
   ["programming", [
                      ["Python", ["pygame"]],
                      ["C#", ["XNA"]],
                   ]
   ],
   ["FOO", [
               ["BAR"]
           ]
   ],
]

最佳答案

这是一个改进的预序树遍历。

http://www.sitepoint.com/print/hierarchical-data-database/

所以输入看起来像这样,一个字典列表。

dbrows = [
   {'title': 'Food', 'lft': 1, 'rgt': 18},
   {'title': 'Fruit', 'lft': 2, 'rgt': 11},
   #etc... etc... from the linked article.
]

使用链接文章中的水果输入。这就是我想要的,排序为 python 列表。

tree = [
        ['Food', [
             ['Fruit', [
                   ['Red', ['Cherry', 'Strawberry']],
                   ['Yellow', ['Banana']],
             ]],
             ['Meat', [
                   ['Beef', 'Pork']
             ]],
        ]],
]

关于python - 将平面数据转换为分层 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1740107/

相关文章:

python - 使用带有 try-except block 的 python "with"语句

python - 如何让Python程序读取文件中的行

python - 使用 Wing IDE 将数据从 dbf 导入到 excel 电子表格

javascript - 多级分层边缘捆绑

port - VHDL - 端口映射 - 将组件的不同端口映射到不同的实体

python - TensorFlow 中的硬限制/阈值激活函数

python - 将数组作为命令行参数传递给 python 脚本

recursion - 如何在Rust中将目录路径的平面列表转换为分层结构?

php - [MySql][PHP] 提取父子树

apache-zookeeper - Zookeeper 整体数据大小限制