在Python中根据邻接列表构建菜单树

1 投票
2 回答
4329 浏览
提问于 2025-04-17 06:38

考虑一个基本的邻接列表;这个列表由一个节点类(Node class)表示,节点有三个属性:id(节点的唯一标识)、parent_id(父节点的标识)和name(节点的名称)。顶层节点的parent_id是None,意思是它们没有父节点。

那么,有什么样的Python方法可以把这个列表转换成一个无序的HTML菜单树呢?比如说:

  • 节点名称
  • 节点名称
    • 子节点名称
    • 子节点名称

2 个回答

2

这是我最终实现的方式——@thg435的方法很优雅,但它是先生成一个字典的列表再打印。而我这个方法会直接打印出一个真正的HTML无序列表(UL)菜单树:

nodes = [ 
{ 'id':1, 'parent_id':None, 'name':'a' },
{ 'id':2, 'parent_id':None, 'name':'b' },
{ 'id':3, 'parent_id':2, 'name':'c' },
{ 'id':4, 'parent_id':2, 'name':'d' },
{ 'id':5, 'parent_id':4, 'name':'e' },
{ 'id':6, 'parent_id':None, 'name':'f' }
]

output = ''

def build_node(node):
    global output
    output += '<li><a>'+node['name']+'</a>'
    build_nodes(node['id']
    output += '</li>'

def build_nodes(node_parent_id):
    global output
    subnodes = [node for node in nodes if node['parent_id'] == node_parent_id]
    if len(subnodes) > 0 : 
        output += '<ul>'
        [build_node(subnode) for subnode in subnodes]
        output += '</ul>'

build_nodes(None) # Pass in None as a parent id to start with top level nodes

print output

你可以在这里查看:http://ideone.com/34RT4

我的方法使用了递归(很酷)和一个全局输出字符串(不太酷)

肯定有人可以在这个基础上做得更好,不过现在对我来说这个方法是有效的..

5

假设你有这样的东西:

data = [

    { 'id': 1, 'parent_id': 2, 'name': "Node1" },
    { 'id': 2, 'parent_id': 5, 'name': "Node2" },
    { 'id': 3, 'parent_id': 0, 'name': "Node3" },
    { 'id': 4, 'parent_id': 5, 'name': "Node4" },
    { 'id': 5, 'parent_id': 0, 'name': "Node5" },
    { 'id': 6, 'parent_id': 3, 'name': "Node6" },
    { 'id': 7, 'parent_id': 3, 'name': "Node7" },
    { 'id': 8, 'parent_id': 0, 'name': "Node8" },
    { 'id': 9, 'parent_id': 1, 'name': "Node9" }
]

这个函数会遍历列表,创建树形结构,并把每个节点的子节点收集到sub列表里:

def list_to_tree(data):
    out = { 
        0: { 'id': 0, 'parent_id': 0, 'name': "Root node", 'sub': [] }
    }

    for p in data:
        out.setdefault(p['parent_id'], { 'sub': [] })
        out.setdefault(p['id'], { 'sub': [] })
        out[p['id']].update(p)
        out[p['parent_id']]['sub'].append(out[p['id']])

    return out[0]

举个例子:

tree = list_to_tree(data)
import pprint
pprint.pprint(tree)

如果父节点的ID是None(而不是0),可以这样修改这个函数:

def list_to_tree(data):
    out = {
        'root': { 'id': 0, 'parent_id': 0, 'name': "Root node", 'sub': [] }
    }

    for p in data:
        pid = p['parent_id'] or 'root'
        out.setdefault(pid, { 'sub': [] })
        out.setdefault(p['id'], { 'sub': [] })
        out[p['id']].update(p)
        out[pid]['sub'].append(out[p['id']])

    return out['root']
    # or return out['root']['sub'] to return the list of root nodes

撰写回答