像数组一样打印单个列表,问题是当我不希望它出现时,最后一个逗号仍然存在
Printing a singly list like an array, problem is last comma still stays when I don't want it to
def printList(self):
node=self.head
#check if list is empty (when there is no head element)
if self.head is None:
print("Empty List")
return
#prints list if not empty
print("[",end="")
while node is not None:
print(node.val, end=",")
node = node.next
print("]")
这是我目前所拥有的,我得到的输出是
[A,A,B,]
只是想知道是否有更简单的方法来删除最后一个字符
我无法回答,但我已经回答了
if node.next is None:
print(node.val, end="")
我能想到的一种方法是使用 list
存储数据并使用 join
从中形成 str
示例:
#using join
my_list = []
for i in range(10):
my_list.append(i)
my_str = ', '.join(str(j) for j in my_list)
print(my_str)
print(f'[{my_str}]')
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
如果你只想将一个字符串列表变成一个字符串,使用 join:
",".join(something_iterable)
例如:
>>> this_is_a_list = [ "AA", "BB", "CC" ]
>>> print(",".join(this_is_a_list))
AA,BB,CC
def printList(self):
node=self.head
#check if list is empty (when there is no head element)
if self.head is None:
print("Empty List")
return
#prints list if not empty
print("[",end="")
while node is not None:
print(node.val, end=",")
node = node.next
print("]")
这是我目前所拥有的,我得到的输出是
[A,A,B,]
只是想知道是否有更简单的方法来删除最后一个字符
我无法回答,但我已经回答了
if node.next is None:
print(node.val, end="")
我能想到的一种方法是使用 list
存储数据并使用 join
str
示例:
#using join
my_list = []
for i in range(10):
my_list.append(i)
my_str = ', '.join(str(j) for j in my_list)
print(my_str)
print(f'[{my_str}]')
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
如果你只想将一个字符串列表变成一个字符串,使用 join:
",".join(something_iterable)
例如:
>>> this_is_a_list = [ "AA", "BB", "CC" ]
>>> print(",".join(this_is_a_list))
AA,BB,CC