Skip to main content
 首页 » 编程设计

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

2025年05月04日6webabcd

我的数据库中有一个数据模型。这是一个按左值排序的扁平 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'] 
             ]], 
        ]], 
]