打印清单列表
问题描述:
我正在学习通过设计家族树来制作清单清单。下面是我提出的一种方法,但是在打印结果时遇到麻烦。例如:打印清单列表
如果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'))
答
你可以使用__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'))
答
这是从输入和输出拆分对象创建一个好主意。此外,使用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]]
当你建立你不能打印树它...(除非你按顺序构建它)。 – alfasin
相关:[在Python中打印树数据结构](http://stackoverflow.com/questions/20242479/printing-a-tree-data-structure-in-python) – DaoWen