根据元素值将一维列表转换为多维(父/子)列表



我正在处理一段数据,需要将其结构化为父/子类型的东西。

这是我掌握的数据。示例的标题和内容已修改。就数据而言,级别键是这里的主要内容。

[
{
"content": null,
"level": 1,
"number": null,
"title": "Level 1 title"
},
{
"content": null,
"level": 2,
"number": "1",
"title": "Level 2 title (1)"
},
{
"content": "Level 3 content (1.1)",
"level": 3,
"number": "(ހ)",
"title": null
},
{
"content": "Level 3 content (1.2)",
"level": 3,
"number": "(ހ)",
"title": null
},
{
"content": "Level 3 content (1.3)",
"level": 3,
"number": "(ނ)",
"title": null
},
{
"content": null,
"level": 2,
"number": "2",
"title": "Level 2 title (2)"
},
{
"content": "Level 3 content (2.1)",
"level": 3,
"number": "(ހ)",
"title": null
},
{
"content": "Level 3 content (2.2)",
"level": 3,
"number": "(ހ)",
"title": null
},
]

我想做的是通读这个列表,最后得到以下

[
{
"content": null,
"level": 1,
"number": null,
"title": "Level 1 title",
"children": [
{
"content": null,
"level": 2,
"number": "1",
"title": "Level 2 title (1)",
"children": [
{
"content": "Level 3 content (1.1)",
"level": 3,
"number": "(ހ)",
"title": null
},
{
"content": "Level 3 content (1.2)",
"level": 3,
"number": "(ހ)",
"title": null
},
{
"content": "Level 3 content (1.3)",
"level": 3,
"number": "(ނ)",
"title": null
}
]
},
{
"content": null,
"level": 2,
"number": "2",
"title": "Level 2 title (2)",
"children": [
{
"content": "Level 3 content (2.1)",
"level": 3,
"number": "(ހ)",
"title": null
},
{
"content": "Level 3 content (2.2)",
"level": 3,
"number": "(ހ)",
"title": null
}
]
}
]
},
]

我尝试过的

我尝试将级别相同的所有项目分组,并将其附加到父项。但后来我立刻感到困惑,并停了下来。

下面是我的尝试,尝试跟踪当前和父节级别和索引。

parent_section = None
parent_section_idx = 0
current_level = 0
next_level = 0
for i, section in enumerate(chunk):
current_level = section.level
if section.level == current_level:
parent_section = section
parent_section_idx = i
if section.level == next_level:
chunk[parent_section_idx].children.append(section)
# parent_section.children.append(section)
if section.level != current_level:
next_level += 1
parent_section = section

我找不到关于这个特定场景的问题。大多数类似的问题都是从多维到一维的。对不起,我缺乏研究。

所以我不知道这是否能对你有所帮助,但这里有一个(丑陋的(例子,说明了什么可以实现你想要实现的目标:

def imbricate(sections_list):
index_at = 0
def sub_imbricate(child_list, at_level):
nonlocal index_at
nonlocal sections_list
while index_at < len(sections_list):
section = sections_list[index_at]
if section['level'] > at_level:
if not 'children' in child_list[-1].keys():
child_list[-1]['children'] = []
sub_imbricate(child_list[-1]['children'], section['level'])
elif section['level'] == at_level:
child_list.append(section.copy())
index_at += 1
elif section['level'] < at_level:
return child_list
return child_list
return sub_imbricate([], 1)

它可以做得更好,而且不处理异常,但也许你可以从这个片段中更好地了解如何实现目标。

我有点困惑,是否应该存在两个连续条目可以具有其"的情况;电平";属性相差不止一个。

不管怎样,你只需要通过增加或减少你的";电平";根据我的理解。

注意:您可能已经知道了,但要在python中测试JSON而不拆包它,您只需将null值替换为"无";并且瞧,Wholething=<复制粘贴>

最新更新