Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python 3将列表添加为树的子级_Python_List_Python 3.x_Tree_Iteration - Fatal编程技术网

使用python 3将列表添加为树的子级

使用python 3将列表添加为树的子级,python,list,python-3.x,tree,iteration,Python,List,Python 3.x,Tree,Iteration,我已经研究过许多非常类似的问题,但无法得出这样的结论: 我有这样一个字符串: {121{12}12{211}2} 我想将字符串读入如下树: {121{12}12{211}2} 我很困惑如何告诉python将整个列表添加为子节点 我还想知道如何将当前节点更改为旧当前节点的父节点 以下是我目前的代码: class Node: def __init__(self,val): self.value = val self.children = []

我已经研究过许多非常类似的问题,但无法得出这样的结论:

我有这样一个字符串:

{121{12}12{211}2}
我想将字符串读入如下树:

{121{12}12{211}2}

我很困惑如何告诉python将整个列表添加为子节点

我还想知道如何将当前节点更改为旧当前节点的父节点

以下是我目前的代码:

class Node:
    def __init__(self,val):
        self.value = val
        self.children = []
        #init Node class so we can pass in values as nodes and set children to empty list

    def add_child(self, obj):
        self.children.append(obj)

s=[]

for i in filedata:
    if i == leftbrace:
        n = Node(i)
    #create new child of current node
    s = []
    #reset list s to blank

if i == rightbrace:
    n.add_child(s)
    #add list s to current node
    #make parent of current node the new current node

else:
    s.append(i)
    #add i to list s

for c in n.children:
    print (c.data)

要使类似的工作正常,使用递归是最简单的。这里有一种方法可以做到这一点

代码:

class Node:
    def __init__(self, stream):
        val = []
        children = []
        while True:
            try:
                # get the next character from the stream
                ch = next(stream)

                # if this is an open brace, then recurse to a child
                if ch == '{':
                    children.append(Node(stream))

                # if this is a close brace, we are done on this level
                elif ch == '}':
                    break

                # otherwise add this character to our value
                else:
                    val.append(ch)

            # stream is empty, we are done
            except StopIteration:
                break

        self.value = ''.join(val)
        self.children = children

    @classmethod
    def from_string(cls, string):
        stream = iter(string)
        tree_top = Node(stream)

        # assert that the string started with '{' and was one top node
        assert len(tree_top.children) == 1 and tree_top.value == ''
        return tree_top.children[0]

    def __str__(self):
        return self.value

    def __repr__(self):
        return "Node('%s', <%d children>)" % (
            self.value, len(self.children))

    def tree_string(self, level=0):
        yield '-' + "  " * level + str(self)
        for child in self.children:
            for child_string in child.tree_string(level+1):
                yield child_string

tree = '{121{12}12{211}2}'
for line in Node.from_string(tree).tree_string():
    print(line)
-121122
-  12
-  211

任何地方都有类定义吗?您似乎没有堆栈的概念,也没有递归函数。我建议您向节点添加一个“parent”属性,并在
add_child
操作期间对其进行初始化。嘿,谢谢,这正是我需要的,但我仍然需要一些帮助来理解repr函数-您可以给我指一个教程吗?所以,我知道。。。转到此页面顶部的搜索栏,然后输入
python repr
。在结果页面上,单击选项卡以按投票排序,顶部为: