简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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