Python 像数组一样打印单个列表,问题是当我不使用';我不想这样
这就是我到目前为止得到的结果,我得到的结果是Python 像数组一样打印单个列表,问题是当我不使用';我不想这样,python,python-3.x,singly-linked-list,Python,Python 3.x,Singly Linked List,这就是我到目前为止得到的结果,我得到的结果是 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
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="")
如果只想将字符串列表转换为一个字符串,请使用“连接”:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
例如:
>>这是一个列表=[“AA”、“BB”、“CC”]
>>>打印(“,”.join(这是一个列表))
AA,BB,CC
链接答案需要创建一个与整个结构重复的列表(这可能不可取)。在代码中可以做的是在循环之前初始化一个分隔符变量,如comma=“”
,在打印每个值之前打印它print(comma,end=“”)
,并在打印后将其分配给实际的分隔符comma=“,”
。
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
",".join(something_iterable)