如果我有这棵树:
# 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)
但没能成功。
1条答案
按热度按时间y0u0uwnf1#
创建另一个树作为副本,然后直接更改其 * root *
descendants
,如下所示: