Python - 如何不使用任何库构建树

-1 投票
0 回答
40 浏览
提问于 2025-04-12 04:23

我需要在Python中制作一个**树形结构**,并且要有箭头和缩进。我不能使用任何库。

It should work like this: 
INPUT:
[[[1, [True, ['abc', 'def']]], [2, [3.14159, 6.023e23]]], 42]

PARAMS:
    indent = 4
    separator = '.'

OUTPUT:
42
├──>1
│...└──>True
│.......├──>abc
│.......└──>def
└──>2
....├──>3.14159
....└──>6.023e+23



[6, [[[[1, [2, 3]], [42, [-43, 44]]], 4], 5]]

PARAMS:
    indent = 2
    separator = ' '

OUTPUT:
6
└>5
  └>4
    ├>1
    │ ├>2
    │ └>3
    └>42
      ├>-43
      └>44

我现在有了这段代码,但它没有连接线。我需要知道子节点的长度,并把它们连接起来。

# Description: Function to print a tree structure
def render_tree(tree: list = None, indent: int = 2, separator: str = ' ') -> str:
    
    #exception handling
    if tree is None or not isinstance(tree, list) or indent <= 1 or len(tree) < 2:
        raise Exception('Invalid tree')
    
    def printnode (depth, parent):
        for inx, child in enumerate (parent): 
            
            #print first element
            if (depth == 0 and type(child) != list):
                print(f"{child}")
                
            #print the rest of the elements
            elif (type(child) != list): 
                if inx == len(parent) - 1:
                    print(f"{separator * (depth -1)}└>{child}")      #Depth * indent  addd       
                else:
                    print(f"{separator * (depth -1)}├>{child}")         
        
        #loop to print the nested lists
        for child in parent:
            if (type(child) == list ): 
                printnode(depth+1, child )

    #initial call      
    printnode(0, tree)
    return ''

输入的数据大多数是:

tree1 =[[[1, [True, ['abc', 'def']]], [2, [3.14159, 6.023e23]]], 42]
tree2 =[[[1, [[True, ['abc', 'def']], [False, [1, 2]]]], [2, [3.14159, 6.023e23, 2.718281828]], [3, ['x', 'y']], [4, []]], 42]
tree3 =[6, [[[[1, [2, 3]], [42, [-43, 44]]], 4], 5]]
tree4 =[6, [5, ['dva\nradky']]]

我尝试为父节点的长度创建一个变量,但这种方法没有得到任何结果。

0 个回答

暂无回答

撰写回答