首页 > 解决方案 > 如何修改我的 print_list 以使其看起来像 [1, 2, 3]?

问题描述

还有其他我没有包含的代码,因为我认为它不相关

我有的:

def print_list(node):
    print('[', end=" ")

    while node:
        print(node)
        if node.next:
            print(',', end=" ")
        node = node.next

    print(']')

我得到以下输出:

[ 1
, 2
, 3
]

它现在已修复,对于任何想要更正版本的人,谢谢 JohanC(:

def print_list(node):
    print('[', end="")
    while node:
        print(node, end="")
        if node.next:
            print(',', end=" ")
        node = node.next
    print(']')


print_list(node1)

标签: python

解决方案


也许你也不想在之后换行print(node)

def print_list(node):
    print('[', end="")

    while node:
        print(node, end="")
        if node.next:
            print(',', end=" ")
        node = node.next

    print(']')

请注意,print('something')打印出给定的文本,然后开始新的一行。print(']', end=' ')不开始一个新行,而是打印出由 给出的字符串end=,它可以是一个空字符串。


推荐阅读