Python 如何打印层次结构列表?

Python 如何打印层次结构列表?,python,list,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 问题是,我不明白怎么做。。。 有什么帮助或想法吗?我提出这个解决

我对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
问题是,我不明白怎么做。。。
有什么帮助或想法吗?

我提出这个解决方案。至少你举的例子是这样的。如果您需要对以下代码进行任何解释,请提出问题:注释应指导您

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))

你好!你试过什么?到目前为止,你对Python了解多少?请至少尝试一下,并让人们知道你尝试过。为特定目的寻求帮助(如果你不理解某些东西)。这里不是完成作业的地方。非常感谢!你给了我一个如何构建自己的解决方案的好主意!我没有使用+=,而是使用=只。。。