【问题标题】:Nested <ul><li> navigation menu using a recursive Python function使用递归 Python 函数的嵌套 <ul><li> 导航菜单
【发布时间】:2011-02-22 17:55:39
【问题描述】:

我想将此数据结构呈现为无序列表。

menu = [
         [1, 0],
           [2, 1],
           [3, 1],
             [4, 3],
             [5, 3],
               [6, 5],
         [7,1]
        ]

[n][0] 是关键
[n][1] 引用父键

想要的输出是:

<ul>
<li>Node 1</li>

  <ul>
  <li>Node 2</li>
  <li>Node 3</li>

    <ul>
    <li>Node 4</li>
    <li>Node 5</li>

      <ul>
      <li>Node 6</li>
      </ul>

    </ul>

   <li>Node 7</li>
   </ul>

</ul>

我可能不用递归就可以做到这一点,但这并不有趣。用递归解决这个问题的最有效方法是什么?

谢谢!

【问题讨论】:

  • 到目前为止你有什么,它怎么不工作?

标签: python recursion menu navigation


【解决方案1】:
def render(nodes, parent = 0):
    if parent not in nodes:
        return
    print('<ul>')
    for n in nodes[parent]:
        print('<li>Node %d</li>' % n)
        render(nodes, n)
    print('</ul>')

这是输出

>>> nodes = {}
>>> for n in menu:
    if n[1] not in nodes:
        nodes[n[1]] = []
    nodes[n[1]].append(n[0])
>>> render(nodes)
<ul>
<li>Node 1</li>
<ul>
<li>Node 2</li>
<li>Node 3</li>
<ul>
<li>Node 4</li>
<li>Node 5</li>
<ul>
<li>Node 6</li>
</ul>
</ul>
<li>Node 7</li>
</ul>
</ul>

【讨论】:

    【解决方案2】:

    即使你的结构很简单,我也不会使用二元素列表。使用一些TreeNode 类,并给它一个适当的__str__ 方法,例如

    class TreeNode(object):
        # ...
        # methods for adding children (instances of TreeNode again) etc.
    
        def __str__(self):
            ret = "<li>%s" % self.value
    
            if self.children:
                children = "".join([str(c) for c in self.children])
                ret += "<ul>%s</ul>" % children 
            ret += "</li>"
    
            return ret
    

    ... 或类似的东西。不过没测试。用&lt;ul&gt; 标记将整个树的表示括起来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多