访问任意树上的特定子项



我已经开始使用anytree但目前在我的树上迭代时面临一些挑战。

测试树:

top = Node("top", keywords="topleveltree")
hello = Node("hello", keywords="hello", parent=top)
hello1 = Node("hello X", keywords="hello X", answer="Say hello to X", parent=hello)
hello2 = Node("hello Y", keywords="hello Y", answer="Say hello to Y", parent=hello)
goodbye = Node("goodbye", keywords="goodbye", parent=top)
goodbye1 = Node("goodbye X", keywords="goodbye X", answer="Say goodbye to X", parent=goodbye)

渲染树:

Node('/top', keywords='topleveltree') ├── Node('/top/hello', keywords='hello') │ ├── Node('/top/hello/hello X', answer='Say hello to X', keywords='hello X') │ └── Node('/top/hello/hello Y', answer='Say hello to Y', keywords='hello Y') └── Node('/top/goodbye', keywords='goodbye') └── Node('/top/goodbye/goodbye X', answer='Say goodbye to X', keywords='goodbye X')

我的脚本检索我的树的第一级(/top/hello 和/top/goodbye(,现在我基本上试图获取它们下面的任何内容(尤其是关键字和答案(。

我已经能够使用多种方式来实现这一点,例如hello.descendants或仅使用LevelOrderIter(hello),但是我现在正在尝试使用某种 python 逻辑(变量现在是字符串(来做同样的事情。

我试图运行 Node(hello(.descendants,但它返回一个空数组。但是,如果我运行type(hello)并且type(Node('hello'))两者都返回<class 'anytree.node.node.Node'>

前任:

categories = ['hello','goodbye']
for category in categories:
print category # string
print Node(category) # Node('/hello')
print hello # Node('/top/hello', keywords='hello')
hello.descendants # ok
Node(category).descendants # ()
[node.name for node in PreOrderIter(hello, maxlevel=3)] # ok
[node.name for node in PreOrderIter(Node('hello'), maxlevel=3)] # return empty 

我对树的经验很少,所以我想我错过了一些基本的东西,但找不到什么。

要访问树子,我们可以使用索引。像 parent.children[1].name 一样,这给了我树中子项 1 的数据。请参阅下面的代码

通过这个代码,我只是在创造孩子:

Start_point={
"man":False,
"goat":False,
"lion":False,
"grass":False,
"state":True
}
udo = Node(Start_point)

# East conditions
temp=dict(udo.name)
for i in temp:
if(temp["state"]==True):
temp=dict(udo.name)
if (i=="man" and temp["man"]==False):
left=dict(temp)
left["man"]=True
Node(left,parent=udo)
if (temp["man"]==False):
temp["man"]=True
if (i=="goat" and temp["goat"]==False):
mid1=dict(temp)
mid1["goat"]=True
Node(mid1,parent=udo)
elif (i=="lion" and temp["lion"]==False):
mid2=dict(temp)
mid2["lion"]=True
Node(mid2,parent=udo)
elif (i=="grass" and temp["grass"]==False):
right=dict(temp)
right["grass"]=True
Node(right,parent=udo)

for pre, fill, node in RenderTree(udo):
print("%s%s" % (pre, node.name))   

其结果:

{'man': False, 'goat': False, 'lion': False, 'grass': False, 'state': True}
├── {'man': True, 'goat': False, 'lion': False, 'grass': False, 'state': True}
├── {'man': True, 'goat': True, 'lion': False, 'grass': False, 'state': True}
├── {'man': True, 'goat': False, 'lion': True, 'grass': False, 'state': True}
└── {'man': True, 'goat': False, 'lion': False, 'grass': True, 'state': True}

访问子级的主要代码:

udo.children[1].name

结果:

{'man': True, 'goat': True, 'lion': False, 'grass': False, 'state': True}

通过这种方式,我得到了child[1]的数据

通过更改索引,我能够获得特定的孩子。

最新更新