【发布时间】:2021-08-14 18:52:04
【问题描述】:
给定一个包含元组的称为轮廓的列表:(级别,标题),创建一个嵌套字典,其深度基于级别,键值基于标题。
示例列表:
[(1, 摘要)
(2、背景)
(2、方法)
(2、结果)
(3、统计)
(3, 图片)
(一、简介)]
这应该输出:
{
"Abstract": {
"Background": {},
"Methods": {},
"Results": {
"Statistics": {},
"Images": {}
}
},
"Introduction": {}
}
到目前为止,我已经尝试了一种递归解决方案,但到目前为止已经导致无法追踪的错误行为。这是迄今为止我提出的最佳解决方案,但由于预定义的 for 循环,我无法防止不同级别的重复:
def structure(outlines, current_level=1, previous_title=''):
section = dict()
for i, (level, title) in enumerate(outlines):
if level == current_level:
section[title] = {}
previous_title = title
elif level > current_level:
section[previous_title] = structure(outlines[i:], level)
elif level < current_level:
pass # Unknown
return section
有什么建议吗?
【问题讨论】:
-
如果两个可能的父节点具有相同的深度,由什么决定应该选择哪一个?
-
@JohnPaulR 存在顺序:如果等级增加,就会成为上一个节点的子节点。连续的同级节点将成为兄弟节点。
-
好的,我根据这个信息更新了答案。
标签: python json dictionary recursion formatting