text-mode tree viewer?

Torsten Bronger bronger at physik.rwth-aachen.de
Tue Jun 26 09:04:23 EDT 2007


Hallöchen!

Martin Skou writes:

> Not quite, but almost:
>
>
> data=[["Peter",
>            ["Ian",
>           [["Randy",
>                      ["Clara"]]]]],
>   "Paul",
>  ["Mary",
>            ["Arthur"]]]

This was flawed, there were two brackets too much:

data=[["Peter",
           ["Ian",
           ["Randy",
                     ["Clara"]]]],
  "Paul",
 ["Mary",
           ["Arthur"]]]

> def show(data,level):
> 	for i in data:
> 		if i.__class__.__name__=='list':
> 			show(i,level+1)
> 		else:
> 			print '%s->%s' % ('-'*level,i)
> 		
> 		
> show(data,0)

It doesn't show Paul and Mary on the same level.  I (think I) solved
the problem with this:

def print_tree(tree, line_columns=[0]):
    for i, item in enumerate(tree):
        current_line = u""
        for j, pos in enumerate(line_columns):
            current_line += (pos - j) * " " + "|"
        print current_line
        if isinstance(item, list):
            print current_line[:-1] + "+---> " + item[0]
            new_line_columns = line_columns + [line_columns[-1] + 6 + len(item[0]) // 2]
            if i == len(tree) - 1:
                del new_line_columns[-2]
            print_tree(item[1], new_line_columns)
        elif isinstance(item, basestring):
            print current_line[:-1] + "+---> " + item

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
                                      Jabber ID: bronger at jabber.org
                      (See http://ime.webhop.org for ICQ, MSN, etc.)



More information about the Python-list mailing list