回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有以下清单:</p>
<pre><code>a = [(1, 1), (2, 1), (3, 1), (4, 3), (5, 3), (6, 3), (7, 7), (8, 7), (9, 7)]
</code></pre>
<p>这是一个元组列表。元组中的元素的格式为<code>(Id, ParentId)</code>无论何时<code>Id == ParentId</code>都是其根节点。列表可以按元组的任何顺序排列。</p>
<p>我想用上面的元组列表生成下面的字典</p>
<pre><code>output = [{
'id': 1,
'children': [{
{
'id': 3,
'children': [{
{
'id': 5
},
{
'id': 4
},
{
'id': 6
}
}]
},
{
'id': 2
}
}]
}, {
'id': 7,
'children': [{
{
'id': 9
},
{
'id': 8
}
}]
}]
</code></pre>
<p>ie(用图形表示-a forrest)</p>
<pre><code> 1 7
/ \ / \
2 3 8 9
/|\
4 5 6
</code></pre>
<p>我的最终输出应该是上面给出的字典。</p>
<p>我尝试了以下方法:</p>
<p>我试过的解决办法如下:</p>
<pre><code># set the value of nested dictionary.
def set_nested(d, path, value):
reduce(lambda d, k: d.setdefault(k, {}), path[:-1], d)[path[-1]] = value
return d
# returns the path of any node in list format
def return_parent(list, child):
for tuple in list:
id, parent_id = tuple
if parent_id == id == child:
return [parent_id]
elif id == child:
return [child] + return_parent(list, parent_id)
paths = []
temp = {}
for i in a:
id, parent_id = i
temp[id] = {'id': id}
path = return_parent(a, id)[::-1]
paths.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(path) # List of path is created
d = {}
for path in paths:
for n, id in enumerate(path):
set_nested(d, path[:n + 1], temp[id]) # setting the value of nested dictionary.
print d
</code></pre>
<p>我得到的结果是</p>
<pre><code>{
'1': {
'3': {
'6': {
'id': '6'
},
'5': {
'id': '5'
},
'id': '3',
'4': {
'10': {
'id': '10'
},
'id': '4'
}
},
'2': {
'id': '2'
},
'id': '1'
},
'7': {
'9': {
'id': '9'
},
'8': {
'id': '8'
},
'id': '7'
}
}
</code></pre>
<p>我已经接近了,但无法得到确切的结果。还有更好的解决办法吗?</p>