簡體   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