我有一个链接的堆栈类,我遇到了在堆栈中打印元素的问题,每个元素都在一个新行中。链接堆栈类中的 str 函数正在打印新行中的每个元素,这是我想要的,但它甚至会在最后打印一个额外的新行。
class Node:
def __init__(self,item,the_next = None):
self.item = item
self.next = the_next
def __str__(self):
return str(self.item)
class LinkedStack:
def __init__(self):
self.top = None
self.count = 0
def __len__(self):
return self.count
def is_empty(self):
return self.count == 0
def isFull(self):
return False
def reset(self):
self.top = None
self.count = 0
def __str__(self): #im having the issue here whereby it prints a newline even after printing the last element
current = self.top
ans = ""
while not (current is None):
ans += str(current)
ans += '\n'
current = current.next
return ans
if __name__ == "__main__":
L = LinkedStack()
L.push(1)
L.push(2)
L.push(3)
print(L)
我得到的输出是:
3
2
1
#an extra newline printed here which is not wanted
我正在寻找一种方法来即兴创建Linked Stack类中的 str 函数,以便最后摆脱冗余的新行。非常感谢任何帮助。
答案 0 :(得分:2)
为什么不简单地修改__str__
的返回值,如此return ans[:-1]
?因为在向字符串添加元素后总是附加一个新行。
另一方面,编写你的函数可能更好:
def __str__(self):
strs = []
cur = self.top
while cur is not None:
strs = [str(cur)] + strs
cur = cur.next
return '\n'.join(strs)
答案 1 :(得分:2)
您可以在获得下一个项目之前移动添加换行符,并在您添加之前检查它是否为None。
然后进一步优化是将中断条件移动到该点:
while True:
ans += str(current)
current = current.next
if current is None:
break
ans += '\n'