访问任何

2024-03-29 11:44:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经开始使用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/goody),现在我基本上尝试获取它们下面的内容(尤其是关键字和答案)。在

我已经能够使用多种方法来实现这一点,比如hello.descendants,或者仅仅使用LevelOrderIter(hello),但是我现在正尝试使用某种python逻辑(其中的变量现在是一个字符串)来实现这一点。在

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

例如:

^{pr2}$

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


Tags: toanswernodehellotoptypeparentsay
1条回答
网友
1楼 · 发布于 2024-03-29 11:44:25

要访问树childer,我们可以使用索引。像父项.子项[1] .name this给我树中child 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))   

结果是:

^{pr2}$

访问子级的主代码:

udo.children[1].name

结果:

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

由此我得到了child[1]的数据

通过改变索引,我可以得到具体的孩子。在

相关问题 更多 >