简体   繁体   中英

How to build a Python anytree tree based on another tree?

If I have this tree:

# 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)

How can I build this other tree (without altering the original)?

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

It has the same structure ("shape"), but each node doesn't have a b attribute and has a c attribute that's "small" if the original node's b was smaller than 6, and "large" if it was >=6.

I've tried to iterate over the original tree with something like

for on_this_level in at.LevelOrderGroupIter(root)

but couldn't make it work.

Create another tree as copy, then - change its root descendants directly as shown below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM