python3 - 遍历树并获取所有叶节点兄弟集合
python3 - traverse tree and get all sets of leaf node siblings
我有一个 json 文件,它的结构就像一棵嵌套的树:
{
"sub": [
{
"code": "01",
"name": "a"
},
{
"code": "02",
"name": "b",
"sub": [
{
"code": "0201",
"name": "b1"
},
{
"code": "0202",
"name": "b2",
"sub":[{
"code": "020201",
"name": "b21"
},{
"code": "020202",
"name": "b22"
}]
}]
},
{
"code": "03",
"name": "c",
"sub": [
{
"code": "0301",
"name": "c1"
},
{
"code": "0302",
"name": "c2"
}]
}]
}
我想要一个算法来获取所有叶节点兄弟节点集(只需要名称属性)。在上面的例子中应该 return:
[
['a'],
['b1'],
['b21','b22'],
['c1','c2']
]
请注意,每个元素都是一个叶节点,每个组中的节点都是兄弟节点。
如何在 python3.x 中实现它?
def traverse(tree):
#how to implement this function?
with open('demo.json') as f:
tree = json.load(f)
traverse(tree)
你可以递归地实现这个:检查当前树是否有子节点,然后收集并生成所有作为叶子的子节点的名称。然后,在每个子节点上递归。
def traverse(tree):
if "sub" in tree:
yield [sub["name"] for sub in tree["sub"] if "sub" not in sub]
for sub in tree["sub"]:
yield from traverse(sub)
我有一个 json 文件,它的结构就像一棵嵌套的树:
{
"sub": [
{
"code": "01",
"name": "a"
},
{
"code": "02",
"name": "b",
"sub": [
{
"code": "0201",
"name": "b1"
},
{
"code": "0202",
"name": "b2",
"sub":[{
"code": "020201",
"name": "b21"
},{
"code": "020202",
"name": "b22"
}]
}]
},
{
"code": "03",
"name": "c",
"sub": [
{
"code": "0301",
"name": "c1"
},
{
"code": "0302",
"name": "c2"
}]
}]
}
我想要一个算法来获取所有叶节点兄弟节点集(只需要名称属性)。在上面的例子中应该 return:
[
['a'],
['b1'],
['b21','b22'],
['c1','c2']
]
请注意,每个元素都是一个叶节点,每个组中的节点都是兄弟节点。
如何在 python3.x 中实现它?
def traverse(tree):
#how to implement this function?
with open('demo.json') as f:
tree = json.load(f)
traverse(tree)
你可以递归地实现这个:检查当前树是否有子节点,然后收集并生成所有作为叶子的子节点的名称。然后,在每个子节点上递归。
def traverse(tree):
if "sub" in tree:
yield [sub["name"] for sub in tree["sub"] if "sub" not in sub]
for sub in tree["sub"]:
yield from traverse(sub)