更新时间:2022-11-22 11:27:42
编辑说明:在我给出此答案后,您已经更改了问题中的输入.以下解决方案适用于您的旧输入,其中列表列表为:
EDIT NOTE: You have changed the input in your question after I gave this answer. The following solution pertains to your old input, where the list of lists was:
[['A', 'A1'], ['A1', 'B', 'C'], ['B', 'B1', 'B2'], ['B1', 'b1', 'b2', 'b3'],
['B2', 'd1', 'd2', 'd3', 'd4'], ['C', 'C1', 'C2', 'C3'], ['C1', 'a1', 'a2', 'a3'],
['C2', 'n1', 'n2', 'n3', 'n4'], ['C3', 'x1', 'x2', 'x3', 'x4']]
假设列表列表存储在变量l
中,则可以使用以下for
循环使用字典映射p
来构造希望字典,以跟踪每个键的父节点:>
Assuming your list of lists is stored in variable l
, you can use the following for
loop to construct the desire dictionary with a dictionary mapping p
to keep track of the parent node for each key:
d = {}
p = {}
for k, *s in l:
r = p.get(k, d)[k] = {i: {} for i in s}
p.update({i: r for i in s})
d
将变为:
{'A': {'A1': {'B': {'B1': {'b1': {}, 'b2': {}, 'b3': {}},
'B2': {'d1': {}, 'd2': {}, 'd3': {}, 'd4': {}}},
'C': {'C1': {'a1': {}, 'a2': {}, 'a3': {}},
'C2': {'n1': {}, 'n2': {}, 'n3': {}, 'n4': {}},
'C3': {'x1': {}, 'x2': {}, 'x3': {}, 'x4': {}}}}}}
要使叶节点成为列表,可以从下至上遍历树,并使用集合m
跟踪子节点,以便可以使用集合差异找到要添加到子节点的所有顶部节点.最后是主词典d
:
To make leaf nodes a list, you can traverse the tree from the bottom up and use a set m
to keep track of the child nodes so that you can use set difference to find all the top nodes to add to the main dictionary d
in the end:
p = {}
m = set()
while l:
k, *s = l.pop()
p[k] = {i: p[i] for i in s} if all(i in p for i in s) else s
m.update(s)
d = {i: p[i] for i in p.keys() - m}
d
将变为:
{'A': {'A1': {'B': {'B1': ['b1', 'b2', 'b3'],
'B2': ['d1', 'd2', 'd3', 'd4']},
'C': {'C1': ['a1', 'a2', 'a3'],
'C2': ['n1', 'n2', 'n3', 'n4'],
'C3': ['x1', 'x2', 'x3', 'x4']}}}}