我怎样才能让我的列表以时尚的顺序打印它的元素?

How can I make my list print its elements in a fashioned order?

我目前有一个填充列表,其中充满了从一个节点到另一个节点的路径中的节点。我需要像这样对路径的打印进行样式化:

node -> node -> node -> node ->
node -> node

我目前有这样的代码:

        if len(path) %4 == 0:    
            for i in range(0, len(path)):
                if i+1 % 4 == 0:
                    print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2]+' -> '+print_queue[3]+' -> ')
                    print_queue = []
                else:
                    print_queue.append(path[i])
        if len(path) %4 == 1:
            path.append(' ')
            for i in range(0, len(path)):
                if path[i] == ' ':
                    break
                if i+1 % 4 == 0:
                    print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2]+' -> '+print_queue[3]+' -> ')
                    print_queue = []
                else:
                    print_queue.append(path[i])
        if len(path) %4 == 2:
            path.append(' ')
            for i in range(0, len(path)):
                if path[i] == ' ':
                    break
                if i+1 % 4 == 0:
                    print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2]+' -> '+print_queue[3]+' -> ')
                    print_queue = []
                else:
                    print_queue.append(path[i])
        if len(path) %4 == 3:
            path.append(' ')
            for i in range(0, len(path)):
                if path[i] == ' ':
                    break
                if i+1 % 4 == 0:
                    print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2]+' -> '+print_queue[3]+' -> ')
                    print_queue = []
                else:
                    print_queue.append(path[i])
        if print_queue != []:
            if len(print_queue) == 1:
                print(print_queue[0])
            if len(print_queue) == 2:
                print(print_queue[0]+' -> '+print_queue[1])
            if len(print_queue) == 3:
                print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2])

但是没有打印路径。路径列表已填充,但程序没有给出任何输出。

我需要更改什么才能打印此路径?

您似乎想用“->”打印路径中的每个元素。

print(" -> ".join(path))

应该这样打印。

如果你也想在末尾加一个“->”,只需在打印语句的末尾添加一个

print(" -> ".join(path) + " -> ")

所以 ["a", "b", "c"] 的路径将打印 a -> b -> c ->

如果你想让它在 4 个节点的倍数上断开,你可以先将数组分成 4 个块

path = ["a", "b", "c", "d", "e"]
print(" -> \n".join([" -> ".join(path[i:i+4]) for i in range(0, len(path), 4)]))

这将打印

a -> b -> c -> d -> 
e