python3 - 遍历树并获取所有叶子节点兄弟集

知道脸颊

我有一个 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"
        }]
    }]
}

我想要一个算法来获取所有叶子节点兄弟姐妹集(只需要 name 属性)。在上面的例子中应该返回:

[
 ['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)
tobias_k

你可以递归地实现这个:检查当前树是否有子节点,然后收集并产生所有作为叶子的子节点的名称。然后,只需在每个子节点上递归。

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章