[英]How to build a Python anytree tree based on another 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)
我怎樣才能建立這棵樹(不改變原來的)?
AnyNode(a='root')
├── AnyNode(a='sub0', c="small")
│ ├── AnyNode(a='sub0A', c="large")
│ └── AnyNode(a='sub0B', c="small")
└── AnyNode(a='sub1', c="small")
它具有相同的結構(“形狀”),但每個節點沒有b
屬性,並且具有c
屬性,如果原始節點的b
小於 6,則為“小”,如果為 >=6,則為“大” .
我試圖用類似的東西遍歷原始樹
for on_this_level in at.LevelOrderGroupIter(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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.