如何为族谱树创建列表列表

时间:2016-05-10 16:56:58

标签: python list

python新手。学习创建一个导致列表列表的函数...例如,可以代表家谱的东西。以下是我提出的建议:

def familytree(root):
        many = int(input('How many children does "' + root[0] + '" have? '))
        if many > 0:
            root.append([[] for y in range(many)])
            z = root[1]
            for j in range(many):
                name = [input("Give name of one of " + root[0] + "'s children?")]
                z[j] = name
                familytree(name)
        print(root)

似乎工作......

['A', [['B', [['D', [['G'], ['H']]], ['E', [['I']]]]], ['C', [['F', [['J'], ['K']]]]]]]

...但会产生不必要的括号和打印输出。

有关更好实施的建议吗?

接下来将在Class结构上工作。

2 个答案:

答案 0 :(得分:0)

这里是如何只打印最终结果的。我还简化了一些其他的东西,使它更清晰。

def familytree(root):
    many = int(input('How many children does "' + root[0] + '" have? '))
    if many > 0:
        z = []
        root.append(z)
        for j in range(many):
            name = [input("Give name of one of " + root[0] + "'s children?")]
            z.append(name)
            familytree(name)


root = ['A']
familytree(root)
print(root)

答案 1 :(得分:0)

一种更简单的方法,不会破坏您的代码:

root = ['A']
def familytree(root):
    many = int(input('How many children does "' + root[0] + '" have? '))
    if many > 0:
        root.extend([] for y in range(many))
        for j in root[1:]: 
            name = input("Give name of one of " + root[0] + "'s children? ")
            j.append(name)
            familytree(j)

print(familytree(root)) 

您也可以使用pprint内置库来打印漂亮的对象

相关问题