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

标签 python list python-3.x tree iteration

我看过很多非常相似的问题,但无法弄清楚:

我有一个像这样的字符串:

{121{12}12{211}2}

我想将字符串读入树中,如下所示:

Tree diagram

我很困惑如何告诉 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

关于python - 使用 python 3 将列表添加为树的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599854/

相关文章:

python - Postgres SSL SYSCALL 错误 : EOF detected with python and psycopg

python - 将颜色条作为图例添加到 matplotlib 散点图(多个子图,多个散点图)

python - 按字符串中单词的数量对字符串列表进行排序

javascript - 使用 Scrapy 抓取无限滚动的网站

python - PyGame 在 macOS 上比在 Ubuntu 或 Raspbian 上慢

python - 如何编写一个知道单元格输入数字的单元格魔术?

list - 如何在 F# 中的类型声明中声明列表

python - 将txt文件转换为列表并在用户输入搜索后返回行

python - 更改目录中文件的名称: Python

python - 使用不能为空的 ListField 定义 mongoengine 模型