1

基本的な隣接リストを考えてみましょう。idプロパティ、parent_id、およびを持つ Node クラスによって表されるノードのリストname。最上位ノードのparent_id = None。

リストを順序付けされていない html メニュー ツリーに変換する Pythonic の方法は次のとおりです。

  • ノード名
  • ノード名
    • サブノード名
    • サブノード名
4

2 に答える 2

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
于 2011-11-19T11:02:41.827 に答える
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

私は再帰(クール)とグローバル出力文字列(クールではない)を使用します

誰かがこれを確実に改善できるかもしれませんが、今のところ私にとってはうまくいっています..

于 2011-11-20T18:25:31.760 に答える