Python - '对象不能被解释为索引'错误

0 投票
1 回答
6061 浏览
提问于 2025-04-16 13:11

我在我的Dijkstra算法代码中遇到了一个我不明白的错误 - 这是错误信息:

Traceback (most recent call last):
  File "C:\Documents and Settings\Harvey\Desktop\algorithm.py", line 52, in <module>
    tentativeDistance(currentNode,populateNodeTable())
  File "C:\Documents and Settings\Harvey\Desktop\algorithm.py", line 29, in tentativeDistance
    currentDistance = nodeTable[currentNode].distFromSource + network[currentNode][nearestNeighbour] #gets current distance from source
TypeError: object cannot be interpreted as an index

这是我的代码:

infinity = 1000000
invalid_node = -1
startNode = 0

class Node:
     distFromSource = infinity
     previous = invalid_node
     visited = False

def populateNodeTable(): 
    nodeTable = []
    index =0
    f = open('route.txt', 'r')
    for line in f: 
      node = map(int, line.split(',')) 
      nodeTable.append(Node()) 
      print nodeTable[index].previous 
      print nodeTable[index].distFromSource 
      index +=1
    nodeTable[startNode].distFromSource = 0 
    #currentNode = nodeTable[startNode] 

    return nodeTable

def tentativeDistance(currentNode, nodeTable):
    nearestNeighbour = []
    #j = nodeTable[startNode]
    for currentNode in nodeTable:
      currentDistance = nodeTable[currentNode].distFromSource + network[currentNode][nearestNeighbour] #gets current distance from source
      if currentDistance != 0 & NodeTable[currentNode].distFromSource < Node[currentNode].distFromSource:
         nodeTable[currentNode].previous = currentNode
         nodeTable[currentNode].length = currentDistance
         nodeTable[currentNode].visited = True
         nodeTable[currentNode] +=1
         nearestNeighbour.append(currentNode)
      print nearestNeighbour

    return nearestNeighbour

currentNode = startNode

if __name__ == "__main__":
    populateNodeTable()
    tentativeDistance(currentNode,populateNodeTable())

我的第一个函数运行得很好,逻辑也没问题,但在网上找解决办法却没有找到。

1 个回答

3

在Python中,for循环的工作方式是这样的,你不需要写

for currentNode in nodeTable:
    currentDistance = nodeTable[currentNode].distFromSource + network[currentNode][nearestNeighbour] #gets current distance from source

你应该这样写:

for currentNode in nodeTable:
    currentDistance = currentNode.distFromSource + network[currentNode][nearestNeighbour]

假设network是一个字典,里面的键是节点,这样写就没问题了。

撰写回答