嵌套- 使用递归 Python 函数的导航菜单
我想将此数据结构呈现为无序列表。
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>
我可能可以在不使用递归的情况下完成此操作,但这并不有趣。用递归解决这个问题最有效的方法是什么?
谢谢!
I want to render this data structure as an unordered list.
menu = [
[1, 0],
[2, 1],
[3, 1],
[4, 3],
[5, 3],
[6, 5],
[7,1]
]
[n][0] is the key
[n][1] references the parent key
The desired output is:
<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>
I could probably do this without recursion but that would be no fun. What is the most efficient way to solve this problem with recursion?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是输出
Here is the output
即使您的结构如此简单,我也不会使用二元素列表。使用一些
TreeNode
类,并给它一个适当的__str__
方法,例如......或类似的东西。不过没有测试过。将整个树的表示包含在
标记中。
I would not use two-element lists, even if your structure is that simple. Use some
TreeNode
class, and give it an appropriate__str__
method, e.g.... or something like that. Didn't test it, though. Enclose the whole tree's representation in an
<ul>
tag.