【发布时间】:2018-11-16 04:32:10
【问题描述】:
我有以下代码来生成列表列表的 json 表示。
Levels=[['L1','L1','L2'],
['L1','L1','L3'],
['L1','L2'],
['L2','L2','L3'],
['L2','L2','L1'],
['L3','L2'],
['L4','L2','L1'],
['L4','L2','L4']]
def append_path(root, paths):
if paths:
child = root.setdefault(paths[0], {})
append_path(child, paths[1:])
for p in Levels:
append_path(root, p)
def convert(d):
return [{'name': k, 'children': convert(v) if v else [{}]} for k, v in d.items()]
# Print results
import json
print(json.dumps(convert(root), indent=4))
输出:
[
"name": "L1",
"children": [
{
"name": "L1",
"children":[
{
"name":"L3",
"children":[{}]
},
{
"name":"L1",
"children":[{}]
}]
},
{
"name":"L2",
"children":[{}]
}
]
关卡
Levels=[['L1','L1','L2'],
['L1','L1','L3'],
['L1','L2'],
我还需要编码每个级别的计数
例如,从L1 开始的路径有两个一级子级L1(2) 和L2(1),后跟L2(1) 和L3(1) 用于下一级。
L1(3)-->L1(2)-->L2(1)
-->L3(1)
-->L2(1)
如何在我的 json 输出中编码这个计数。
我希望我的最终输出看起来像这样
"name": "L1(3)",
"children": [
{
"name": "L1(2)",
"children":[
【问题讨论】:
-
您想添加可以从已有数据中提取的值,其格式既不直观也不易于机器读取?
-
“count”是指叶子节点的个数还是节点的高度?
标签: python json python-3.x