繁体   English   中英

将Tree数据结构保存为Python中的dict

[英]Saving a Tree data structure as a dict in Python

我遇到了一篇名为《 用Python打印树数据结构》的文章 ,我喜欢打印树遍历的功能。

我想要的是将输出捕获为字典。 这是我的打印代码:

def print(self, level=0):
    print('{}{}'.format(' '*4*level, self.node_id))
    for child in self.children:
        child.print(level=level+1)

哪个打印如下:

'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

我不知道从哪里开始。

这是一个简单的未优化版本,可为您提供从何处开始的一些线索:

from itertools import takewhile
import json


class node(object):

    def __init__(self, value, children=[]):
        self.value = value
        self.children = children

    def __str__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__str__(level+1)
        return ret

    def __repr__(self):
        return '<tree node representation>'


def build_tree(lines):
    sep = '\t'
    lst, res = [], []
    for line in iter(lines):
        if not line.strip():
            continue
        indent = len(list(takewhile(sep.__eq__, line)))
        lst[indent:] = [line.lstrip()]
        res.append(sep.join(lst[:]))

    tree = {}
    for item in res:
        t = tree
        for part in item.split(sep):
            t = t.setdefault(part, {})
    return tree

if __name__ == "__main__":
    root = node('grandmother')
    root.children = [node('daughter'), node('son')]
    root.children[0].children = [node('granddaughter'), node('grandson')]
    root.children[1].children = [node('granddaughter'), node('grandson')]
    print('text'.center(80, '='))
    source = str(root)
    print(source)
    print('tree'.center(80, '='))
    print(json.dumps(build_tree(source.split("\n")), indent=4))

输出:

======================================text======================================
'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

======================================tree======================================
{
    "'grandmother'": {
        "'daughter'": {
            "'granddaughter'": {},
            "'grandson'": {}
        },
        "'son'": {
            "'granddaughter'": {},
            "'grandson'": {}
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM