如何漂亮地打印层次列表?

时间:2019-05-28 13:19:01

标签: python list

我对Python很陌生,在大学里,我们的老师给了我们以下问题:

他给了我们以下清单:

[ '1,2,3,4', '2,5,6', '3,7,8', '4,9' ]

应该这样:1是2、3、4的主管,而2是5、6的主管,以此类推 因此,我们的老师希望我们编写一个程序来像这样漂亮地打印图形:

1

....2

........5

........6

....3

........7

........8

....4

........9

问题是,我不知道该怎么做... 有什么帮助或想法吗?

1 个答案:

答案 0 :(得分:0)

我提出了这种解决方案。至少它与您给出的示例兼容。如果您需要以下代码的任何解释,请提出问题:这些注释将指导您。

lst_string = ['1,2,3,4', '2,5,6', '3,7,8', '4,9']
# first, transform your list into a nested list

# create an empty list
lst_nested = list()

for seq_string in lst_string:
    to_list = list(seq_string)  # the first list looks like ["1", ",", "2", ",", "3", ",", "4']
    to_list = to_list[0::2]  # this removes the "," inputs
    to_list = list(map(int, to_list))  # this transforms ["1", "2", "3"] into [1,2,3]
    lst_nested.append(to_list)

# define the list of first elements
first_elements = list()
for lst in lst_nested:
    first_elements.append(lst[0])

# prepare the output
tab = "...."

def fill_in(seq, idx_tab):
    # always displays the first element
    output = ""
    output += tab * idx_tab
    output += str(seq[0])
    output += "\n"

    for intgr in seq[1:]:
        if intgr in first_elements: 
            # call recursively function fill_in with the corresponding seq
            output += fill_in(lst_nested[first_elements.index(intgr)], idx_tab + 1)

        else:
            output += tab * (idx_tab + 1)
            output += str(intgr)
            output += "\n"

    return output

print(fill_in(lst_nested[0], 0))