打印列表列表

2024-04-19 04:09:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何通过设计一个家谱来制作列表。下面是一种方法,我想出了,但有麻烦打印结果。例如:

如果A有两个孩子,B&C。。。 B有两个孩子,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'))

Tags: 方法代码nameselfchild图形列表input
2条回答

将对象创建与输入和输出分离是一个好主意。另外,使用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]]

可以使用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'))

相关问题 更多 >