简体   繁体   English

在Python中以树形显示列表列表

[英]Display a list of lists as a tree in Python

I would like to define a function to print a list of lists with common components as a tree. 我想定义一个函数,将具有常见组件的列表列表打印为树。

For example, 例如,

lst = [[1, 2, 'a'], [1, 2, 'b'], [1, 1, 'a'], [1, 1, 'b'], [2, 2, 'a']]
build_tree(lst)

should print: 应该打印:

1
    1
        a
        b
    2
        b
2
    2
        a

I wrote the following code. 我写了下面的代码。

def build_tree(lst):
    if len(lst[0]) == 1:
        for e in lst:
            return str(e[0])
    current = lst[0][0]
    seen = []
    tree = ''
    for e in lst:
        if e[0] != current:
            tree += str(current)
            tree += build_tree(seen)
            current = e[0]
            seen = []
        seen.append(e[1:])
    return tree

But the returned result is nonsense. 但是返回的结果是胡说八道。

One way to solve this would be to change your list into a tree strucutre, then loop over that tree to build the string repersentation of your data 解决此问题的一种方法是将列表更改为树结构,然后在该树上循环以构建数据的字符串表示形式

from collections import defaultdict

tree = lambda: defaultdict(tree)

lst = [[1, 2, 'a'], [1, 2, 'b'], [1, 1, 'a'], [1, 1, 'b'], [2, 2, 'a']]


def make_tree(lst):
    d = tree()    
    for x in lst:
        curr = d
        for item in x:
             curr = curr[item]
    return d

d = make_tree(lst)

def make_strs(d, indent=0):
     strs = []
     for k, v in d.items():
         strs.append('    ' * indent + str(k))
         strs.extend(make_strs(v, indent+1))
     return strs

def print_tree(d):
    print('\n'.join(make_strs(d)))

print_tree(d)

prints 版画

1
    2
        a
        b
    1
        a
        b
2
    2
        a

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

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