擅长:python、mysql、java
<p>要标识根注释,可以解压缩<code>links</code>,并查找不是子级的父级:</p>
<pre><code>parents, children = zip(*links)
root_nodes = {x for x in parents if x not in children}
</code></pre>
<p>然后可以应用递归方法:</p>
<pre><code>import json
links = [("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Bob","Leroy"),("Bob","Earl")]
parents, children = zip(*links)
root_nodes = {x for x in parents if x not in children}
for node in root_nodes:
links.append(('Root', node))
def get_nodes(node):
d = {}
d['name'] = node
children = get_children(node)
if children:
d['children'] = [get_nodes(child) for child in children]
return d
def get_children(node):
return [x[1] for x in links if x[0] == node]
tree = get_nodes('Root')
print json.dumps(tree, indent=4)
</code></pre>
<p>我使用一个集合来获取根节点,但是如果顺序很重要,可以使用列表和<a href="https://stackoverflow.com/questions/10549345/how-to-remove-duplicate-items-from-a-list-using-list-comprehension">remove the duplicates</a>。</p>