如何基于另一棵树构建Python任意树?

4si2a6ki  于 2023-01-29  发布在  Python
关注(0)|答案(1)|浏览(124)

如果我有这棵树:

# mytree.py
import anytree as at
import anytree.importer

data = {
    "a": "root",
    "children": [
        {
            "a": "sub0",
            "b": 3,
            "children": [{"a": "sub0A", "b": 9}, {"a": "sub0B", "b": 1}],
        },
        {"a": "sub1", "b": 5},
    ],
}
root = at.importer.DictImporter().import_(data)
python3 -i mytree.py
print(at.RenderTree(root, style=at.render.ContStyle()))
AnyNode(a='root')
├── AnyNode(a='sub0', b=3)
│   ├── AnyNode(a='sub0A', b=9)
│   └── AnyNode(a='sub0B', b=1)
└── AnyNode(a='sub1', b=5)

我怎样才能构建另一棵树(而不改变原来的树)?

AnyNode(a='root')
├── AnyNode(a='sub0', c="small")
│   ├── AnyNode(a='sub0A', c="large")
│   └── AnyNode(a='sub0B', c="small")
└── AnyNode(a='sub1', c="small")

它具有相同的结构("shape"),但每个节点都没有b属性,而是有一个c属性,如果原始节点的b小于6,则为"small",如果大于等于6,则为"large"。
我试着用类似于

for on_this_level in at.LevelOrderGroupIter(root)

但没能成功。

y0u0uwnf

y0u0uwnf1#

创建另一个树作为副本,然后直接更改其 * root * descendants,如下所示:

import copy

new_root = copy.deepcopy(root)
for dsc in new_root.descendants:
    dsc.c = 'large' if dsc.b >=6 else 'small'
    del dsc.b
    
print(at.RenderTree(new_root, style=at.render.ContStyle()))
AnyNode(a='root')
├── AnyNode(a='sub0', c='small')
│   ├── AnyNode(a='sub0A', c='large')
│   └── AnyNode(a='sub0B', c='small')
└── AnyNode(a='sub1', c='small')

相关问题