码迷,mamicode.com
首页 > 编程语言 > 详细

【Python】用文本打印树

时间:2015-03-11 22:56:16      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

From:http://zhidao.baidu.com/link?url=O8U5TynGBMojDw2iFhlghPPf5_ZE1X8CAQMrK19pv-KxhvKCc6Z2yzsoQaukgN2haYudVO7Hg3c0ZvNm8ALcY_

#!/usr/bin/python3
# -*- coding: utf-8 -*-
 
def print_tree(tree):
    buff = [ROOT/]
    _print_tree(tree, buff, ‘‘, 0)
    print(\n.join(buff))
 
def _print_tree(tree, buff, prefix, level):
    count = len(tree)
    for k, v in tree.items():
        count -= 1
        if v:
            buff.append(%s +- %s/ % (prefix, k))
            if count > 0:
                _print_tree(v, buff, prefix +  |  , level + 1)
            else:
                _print_tree(v, buff, prefix +     , level + 1)
        else:
            buff.append(%s +- %s % (prefix, k))
 
def test():
    tree = {
        bin: { bash: None, cat: None, cp: None, },
        etc: {
            init.d: { apache2:None, slapd:None, sshd:None, },
            passwd: None,
            hosts: None,
        },
        var: {
            log: {
                apache2: { accesslog:None, errorlog: None, },
            },
        },
    }
    print_tree(tree)
 
if __name__ == __main__:
    test()

输出

ROOT/
 +- etc/
 |   +- passwd
 |   +- init.d/
 |   |   +- apache2
 |   |   +- sshd
 |   |   +- slapd
 |   +- hosts
 +- bin/
 |   +- cp
 |   +- bash
 |   +- cat
 +- var/
     +- log/
         +- apache2/
             +- errorlog
             +- accesslog

 

【Python】用文本打印树

标签:

原文地址:http://www.cnblogs.com/colipso/p/4330979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!