gpt4 book ai didi

python - 从标识符构建 json 树结构

转载 作者:行者123 更新时间:2023-11-30 23:43:12 27 4
gpt4 key购买 nike

我有一个包含如下数据的文件:

ID attribute
1 'text'
101 'text'
1011 'text'
10111 'text'
1011101 'text'
1011102 'text'
1011103 'text'
1011104 'text'
1011130 'text'

我的目标是从这些数据构建 json 树结构:

{
[
ID : 1,
attribute : 'text',
children : [
ID: 101,
attribute : 'text',
children : [
...
ID : 2,
...
]
}

在 python 中,我构建了一个这样的字典列表:

[ {'id': ID, 'attr' : text}, {...} ]

我想我可以利用叶子 id 包含他 parent id 的事实,但我看不到构建我想要的结构的方法。

如果您能以伪代码或任何其他编程语言提供帮助,我将不胜感激。

最佳答案

我不太了解你的 ID 编号系统,所以这里是一个简单的前缀树的代码:

ls = """
1 'text'
101 'text'
1011 'text'
10111 'text'
1011101 'text'
2 two
2111 'text'
21114 'text'
25 'text'
2567 'text'
"""
ls = map(str.split, ls.strip().splitlines())


tree = [{'prefix': '', 'children':[]}]
stack = [tree[0]]

for id, attr in ls:
while not id.startswith(stack[-1]['prefix']):
stack.pop()
node = {'prefix': id, 'attr': attr, 'children': []}
stack[-1]['children'].append(node)
stack.append(node)

import pprint
pprint.pprint( tree)

关于python - 从标识符构建 json 树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10969814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com