简体   繁体   English

从Python中的邻接表构建菜单树

[英]Building a menu tree from an adjacency list in Python

Consider a basic adjacency list; 考虑一个基本的邻接表; a list of nodes represent by a Node class, with properties id , parent_id , and name . 由Node类表示的节点列表,其属性为idparent_idname The parent_id of top-level nodes = None. 顶级节点的parent_id =无。

What would be a Pythonic way of transforming the list into an un-ordered html menu tree, eg: 将列表转换为无序html菜单树的Python方式是什么,例如:

  • node name 节点名称
  • node name 节点名称
    • sub-node name 子节点名称
    • sub-node name 子节点名称

Assuming you've got something like this: 假设您有这样的事情:

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" }
]

This function iterates through the list and creates the tree, collecting children of each node is the sub list: 此函数遍历列表并创建树,收集每个节点的subsub列表:

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]

Example: 例:

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

If parent ids are None's (not 0's), modify the function like this: 如果父代ID为“无”(不是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

This is how I ended up implementing it- @thg435's way is elegant, but builds a list of dictionaries to print. 这就是我最终实现它的方式-@ thg435的方式很优雅,但是建立了要打印的词典列表。 This one will print an actual HTML UL menu tree: 这将打印出实际的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

You can see it here: http://ideone.com/34RT4 您可以在这里看到它: http : //ideone.com/34RT4

Mine uses recursion (cool) and a global output string (not cool) 我的使用递归(酷)和全局输出字符串(不酷)

Someone could surely improve on this, but it's working for me right now.. 肯定有人可以对此进行改进,但是它现在对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM