打印列表 returns 每个元素的位置,而不是值

Printing a list returns the location of each element, not the values

我在打印我正在创建的列表时遇到问题。

class Node():
    def __init__(self, cargo = None, next = None):
        self.cargo = cargo
        self.next = next
    def __str__(self):
        return str(self.cargo)

node1 = Node(1)
node2 = Node(2)
node3 = Node(3)

node1.next = node2
node2.next = node3

def printList(node):
    i = 0
    nodeList = []
    while node:
        nodeList.append(node)
        node = node.next
    return nodeList

print(printList(node1))

这是输出:

[<__main__.Node object at 0x0189E470>, <__main__.Node object at 0x0189E950>, <__main__.Node object at 0x0189E7B0>]

我相信我目前得到的输出是每个元素在我的计算机中的存储位置。我想收到的输出是列表格式的 [1, 2, 3]。我可以通过单独打印每个元素来做到这一点,但我宁愿不这样做。谁能给我任何建议?

您的 nodeList 包含 Node 个对象,这些对象是您在打印中得到的对象,打印列表时,所以要么对它们调用打印:

而不是

print(printList(node1))

通话

for nod in printList(node1):
    print(nod)

或者让你的 nodeList 包含节点的字符串表示,因为函数被称为 printList:

  def printList(node):
        i = 0
        nodeList = []
        while node:
            nodeList.append(str(node)) #use str() here
            node = node.next
        return nodeList

print(printList(node1))