[英]How to format the output print statement to print linked list?
So I trying to print the linked list after the string but I not able to do it.所以我试图在字符串之后打印链接列表,但我无法做到。 The print statement is in pop function inside unordered class
打印语句在 pop function 里面无序 class
The linked list always get printed first and then the string ie链表总是先打印,然后是字符串,即
54 26 56 93 17 77 31 7
Original Linked List: None
My Desired Output我想要的 Output
Original Linked List: 54 26 56 93 17 77 31 7原始链表:54 26 56 93 17 77 31 7
class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def printList(self):
temp = self.head
while (temp):
print(temp.data, end=" ")
temp = temp.next
print('\n')
def pop(self):
print('Original Linked List:' self.printList())
current = self.head
previous = None
while current.getNext() != None:
previous = current
current = current.getNext()
previous.setNext(current.getNext())
print('New linked list after pop is:', self.printList())
So I have tried formatting it with所以我尝试用
print(f'Orginal Linked List: {self.printList()})
print('Original Linked List: %d' %(self.printList()))
Nothing really works I am new to programming I appreciate your help.没有什么能真正起作用我是编程新手,感谢您的帮助。
You need a function that returns a list rather than printing a list.您需要一个返回列表而不是打印列表的 function。 It's easiest if you name this function
__str__
because then it'll get called automatically whenever anything tries to convert your list to a string.如果您将其命名为 function
__str__
,这是最简单的,因为只要有任何东西试图将您的列表转换为字符串,它就会被自动调用。
Change:改变:
def printList(self):
temp = self.head
while (temp):
print(temp.data, end=" ")
temp = temp.next
print('\n')
to:至:
def __str__(self):
s = ''
temp = self.head
while temp:
s += str(temp.data) + " "
temp = temp.next
return s[:-1]
and then you can do:然后你可以这样做:
print(f'Original Linked List: {self})
which will automatically call your __str__
method and put the result into the f-string.这将自动调用您的
__str__
方法并将结果放入 f-string。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.