2012-06-20 60 views
0

我正在尋找一個答案在Python中代表一個n-ary樹的目錄。 我認爲文件夾的N-ary樹就是一個很好的例子。這裏是我的代碼:Python的n-ary樹的目錄

class Node(object): 
    def __init__(self, data): 
     self.data = data 
     self.children = [] 

n = Node(sys.argv[1]) 

def walktree(top): # recurse from "/top/" 

    X = [] # clear record 
    for f in os.listdir(top): 
     pathname = os.path.join(top,f) 
     mode = os.stat(pathname)[ST_MODE] 
     if S_ISDIR(mode): # It's a directory 
      X.append(pathname) # 
      walktree(pathname) # recursion 
    X.sort() 
    n.add_child(X) 

我的問題是:

  1. 這段代碼是否正確?
  2. 如何填寫如何遍歷構造N叉樹

答案1,2,3- N叉樹

  • 的給定節點。

    def dirwalk(top): # build an n_ary tree 
        n = Node(top) # ONE Node per folder 
        for f in os.listdir(top): # loop over the current dir 
         pathname = os.path.join(top,f) # dir + fname 
         mode = os.stat(pathname)[ST_MODE] 
         if S_ISDIR(mode): # It's a directory 
          ptr = dirwalk(pathname) # go down 
          n.add_child(ptr) # add pointer to node 
        return n # return Node 
    
    def traverse(n): # traverse buildt tree 
        for p in n: # loop over children 
         print p.data 
         traverse(p.children) 
    
  • +5

    那麼究竟什麼是你的問題? –

    +1

    你知道你可以使用'os.walk()'方法,它也可以像這樣工作嗎? –

    +0

    @IT:其實'os.walk'比這個更普遍。但是我們當然可以在它上面建立這個'walktree'函數。 –

    回答

    0

    在我看來,pythonic的方式來做到這一點只是使用嵌套列表。你可以通過元組(subdirs, files)表示一個目錄,其中subdirsfiles是列表,subdirs包含進一步的元組,files是文件名列表。

    舉例建設,結合namedtuple的建議由尼克拉斯·B:

    import os, os.path 
    from collections import namedtuple 
    
    Directory = namedtuple('Directory', ['path', 'subdirectories', 'files']) 
    
    def walktree(path): 
        dirs = [] 
        files = [] 
        for f in os.listdir(path): 
         if os.path.isdir(os.path.join(path, f)): 
          dirs.append(walktree(os.path.join(path, f))) 
         else: 
          files.append(f) 
        return Directory(path, dirs, files) 
    
    +0

    也許一個'namedtuple('subdirs','files')'會更清晰 –

    0

    這應該是相當瑣碎使用os.walk來實現:

    class Node(): 
        def __init__(self, name): 
         self.name = name 
         self.files = [] 
         self.folders = {} 
        def __str__(self): 
         return '%s: files: %s, folders: %s' % (self.name, self.files, self.folders) 
    
    def find_node(top_node, name): 
        import pdb; pdb.set_trace() 
        result = top_node 
        path = name.split(os.sep)[1:] 
        for path_comp in path: 
         result = result.folders[path_comp] 
    
        return result 
    
    import sys, os 
    tree = Node(sys.argv[1]) 
    for root, folders, files in os.walk(sys.argv[1]): 
        parent_node = find_node(tree, root) 
    
        for folder in folders: 
         parent_node.folders[folder] = Node(folder) 
    
        for file in files: 
         parent_node.files.append(file) 
    
    print tree