2016-05-16 88 views
0

我正在學習通過設計家族樹來製作清單清單。下面是我提出的一種方法,但是在打印結果時遇到麻煩。例如:打印清單列表

如果A有2個孩子,B &ç... 則B有2個孩子,d & E. .. 而C只對孩子,F ...

我會想要打印結果:[A,[B,[D,E]],[C,[F]]]

希望我的代碼有任何改進,關於如何打印上述結果的建議,以圖形形式打印。

class FamilyTree: 
    def __init__(self, root): 
     self.name = [root] 
     nmbr = int(input("How many children does " + root + " have?")) 
     if nmbr is not 0: 
      for i, child in enumerate(range(nmbr)): 
       name = input("What is one of " + root + "'s child's name?") 
       setattr(self, "child{0}".format(i), FamilyTree(name)) 
r = print(FamilyTree('A')) 
+0

當你建立你不能打印樹它...(除非你按順序構建它)。 – alfasin

+0

相關:[在Python中打印樹數據結構](http://stackoverflow.com/questions/20242479/printing-a-tree-data-structure-in-python) – DaoWen

回答

0

你可以使用__str__方法,它是通過print()函數調用:

class FamilyTree: 
    def __init__(self, root): 
     self.name = root 
     self.children = [] 
     nmbr = int(input("How many children does " + root + " have? ")) 
     if nmbr is not 0: 
      for i, child in enumerate(range(nmbr)): 
       name = input("What is one of " + root + "'s child's name? ") 
       self.children.append(FamilyTree(name)) 
    def __str__(self): 
     return '[' + self.name + ''.join(', ' + str(c) for c in self.children) + ']' 
r = print(FamilyTree('A')) 
0

這是從輸入和輸出拆分對象創建一個好主意。此外,使用setattr將使寫入輸出更加困難。

這裏是一個解決方案,允許您創建一個FamilyTree有或沒​​有從用戶讀取輸入:

class FamilyTree: 
    def __init__(self, root, childs = []): 
     self.name = root 
     self.childs = childs 

    def read(self): 
     nmbr = int(input("How many children does " + self.name + " have? ")) 
     if nmbr is not 0: 
      for _ in range(nmbr): 
       name = input("What is one of " + self.name + "'s child's name? ") 
       child = FamilyTree(name) 
       child.read() 
       self.childs.append(child) 

    def __repr__(self): 
     if len(self.childs) == 0: 
      return str("{}".format(self.name)) 
     else: 
      return str("{}, {}".format(self.name, self.childs)) 

# creates a FamilyTree directly so we can test the output 
r = FamilyTree(
     'A', 
     [ 
      FamilyTree(
       'B', 
       [FamilyTree('C'), FamilyTree('C')] 
      ), 
      FamilyTree(
       'C', 
       [FamilyTree('F')] 
      ) 
     ] 
    ) 

# or read input from the user 
# r = FamilyTree('A') 
# r.read() 

print(r) 

輸出

A, [B, [C, C], C, [F]]