gpt4 book ai didi

python - 从路径列表转换为 Flare json 格式?

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:23 28 4
gpt4 key购买 nike

我在 python 中有这样的数据:

[['a', 'b', 'c', 50],
['a', 'b', 'd', 100],
['a', 'b', 'e', 67],
['a', 'g', 'c', 12],
['q', 'k', 'c', 11],
['q', 'b', 'p', 11]]

其中列表的每个元素都是一个完整的层次路径,最后一个元素是路径的大小。要在 D3 中进行可视化,我需要数据采用 flare 数据格式 - 参见此处:

https://github.com/d3/d3-hierarchy/blob/master/test/data/flare.json

所以短片看起来像这样

{
"name": "root",
"children": [
{
"name": "a",
"children": [
{
"name": "b",
"children": [
{"name": "c", "value": 50},
{"name": "d", "value": 100},
{"name": "e", "value": 67},
]
},
{
"name": "g",
"children": [
{"name": "c", "value": 12},
]
},

等等……

从我一直在查找的内容来看,我认为解决方案是递归的,并且会在 Python 字典上使用 json 库,但我似乎无法让它工作。任何帮助是极大的赞赏。

最佳答案

这是一个使用递归的解决方案:

 def add_to_flare(n, flare):
children = flare["children"]

if len(n) == 2:
children.append({"name": n[0], "value": n[1]})
else:
for c in children:
if c["name"] == n[0]:
add_to_flare(n[1:], c)
return

children.append({"name": n[0], "children": []})
add_to_flare(n[1:], children[-1])

flare = {"name": "root", "children": []}

for i in data:
add_to_flare(i, flare)

为了更好地显示它,我们可以使用 json 库:

import json
print(json.dumps(flare, indent=1))

{
"name": "root",
"children": [
{
"name": "a",
"children": [
{
"name": "b",
"children": [
{
"name": "c",
"value": 50
},
{
"name": "d",
"value": 100
},
{
"name": "e",
"value": 67
}
]
},
{
"name": "g",
"children": [
{
"name": "c",
"value": 12
}
]
}
]
},
{
"name": "q",
"children": [
{
"name": "k",
"children": [
{
"name": "c",
"value": 11
}
]
},
{
"name": "b",
"children": [
{
"name": "p",
"value": 11
}
]
}
]
}
]
}

关于python - 从路径列表转换为 Flare json 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53123294/

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