Python 带节点的无序列表:__str__ 方法

Python Unordered Listwith nodes: __str__ method

我正在尝试为我的 UnorderedList class 编写一个 __str__method,它可以允许列表以如下格式打印出来:[1,2,3,4,5]。

但由于某种原因,它只打印出列表的第一个位置。例如。 [1] 而不是 [1,2,3,4,5]

def __str__(self):

    result = "["
    node = self.head
    if node != None:
        result += str(node.data)
        node = node.next
        for i in range(self.num_elements - 1):
            result += ", " + str(node.data)
            node = node.next
    result += "]"
    return result    

这是我剩下的 Node 和 UnorderedList class 方法...

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 add(self,item):
    temp = Node(item)
    temp.setNext(self.head)
    self.head = temp

def size(self):
    current = self.head
    count = 0
    while current != None:
        count = count + 1
        current = current.getNext()
    return count

def search(self,item):
    current = self.head
    found = False
    while current != None and not found:
        if current.getData() == item:
            found = True
        else:
            current = current.getNext()
    return found

def remove(self,item):
    current = self.head
    previous = None
    found = False
    while not found:
        if current.getData() == item:
            found = True
        else:
            previous = current
            current = current.getNext()

    if previous == None:
        self.head = current.getNext()
    else:
        previous.setNext(current.getNext())

def __str__(self):

    result = "["
    node = self.head
    if node != None:
        result += str(node.data)
        node = node.next
        for i in range(0 - 1):
            result += ", " + str(node.data)
            node = node.next
    result += "]"
    return result

任何帮助都会很棒。另外我觉得有一种更简单的方法来编写 str.

你循环不正确(在顶级版本中使用从未设置的 self.num_elements 和在底部版本中强制循环永远不会发生,如 range(0 - 1) 又名 range(-1)当然是[]。可能更好:

def __str__(self):
    result = "["
    node = self.head
    if node != None:
        result += str(node.data)
        node = node.next
        while node:
            result += ", " + str(node.data)
            node = node.next
    result += "]"
    return result    

不同之处在于循环 while node: 而不是试图以某种方式预测或强制涉及的元素数量。

def __str__(self):
    result = "["
    node = self.head
    while node:
        result += ('' if result == '[' else ", ") + str(node.data)
        node = node.next
    result += "]"

    return result