簡體   English   中英

在 Python 中打印樹數據結構

[英]Printing a Tree data structure in Python

我一直在尋找樹打印的可能實現,它以用戶友好的方式打印樹,而不是作為對象的實例。

我在網上遇到了這個解決方案:

資料來源: http ://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html

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

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

此代碼按以下方式打印樹:

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

是否可以在不更改__repr__方法的情況下獲得相同的結果,因為我將它用於其他目的。

是的,將__repr__代碼移動到__str__ ,然后在樹上調用str()或將其傳遞給print語句。 記得在遞歸調用中也使用__str__

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>'

演示:

>>> 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')]
>>> root
<tree node representation>
>>> str(root)
"'grandmother'\n\t'daughter'\n\t\t'granddaughter'\n\t\t'grandson'\n\t'son'\n\t\t'granddaughter'\n\t\t'grandson'\n"
>>> print root
'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

你為什么不將其存儲為一個treelib對象 ,並打印出來類似於我們如何絕版的CHAID樹在這里與有關你的使用情況更相關節點的描述?

([], {0: 809, 1: 500}, (sex, p=1.47145310169e-81, chi=365.886947811, groups=[['female'], ['male']]))
├── (['female'], {0: 127, 1: 339}, (embarked, p=9.17624191599e-07, chi=24.0936494474, groups=[['C', '<missing>'], ['Q', 'S']]))
│   ├── (['C', '<missing>'], {0: 11, 1: 104}, <Invalid Chaid Split>)
│   └── (['Q', 'S'], {0: 116, 1: 235}, <Invalid Chaid Split>)
└── (['male'], {0: 682, 1: 161}, (embarked, p=5.017855245e-05, chi=16.4413525404, groups=[['C'], ['Q', 'S']]))
    ├── (['C'], {0: 109, 1: 48}, <Invalid Chaid Split>)
    └── (['Q', 'S'], {0: 573, 1: 113}, <Invalid Chaid Split>)

不修改__repr____str__解決方案

def other_name(self, level=0):
    print('\t' * level + repr(self.value))
    for child in self.children:
        child.other_name(level + 1)

這個答案是作為對問題Printing a Tree data structure in Python編輯發布的,由 OP Kristof Pal在 CC BY-SA 3.0 下發布。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM