gpt4 book ai didi

python - 使用递归 Python 函数的嵌套
  • 导航菜单

转载 作者:行者123 更新时间:2023-11-28 22:06:55 26 4
gpt4 key购买 nike

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

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>

我或许可以在没有递归的情况下做到这一点,但那将毫无乐趣可言。用递归解决这个问题的最有效方法是什么?

谢谢!

最佳答案

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>

关于python - 使用递归 Python 函数的嵌套 <ul><li> 导航菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2888810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com