我所遇到的一個問題,我不知道如何解決涉及Dijkstra算法 - 這裏是我的代碼:int對象可迭代
infinity = 1000000
invalid_node = -1
#startNode = 0
class Node:
distFromSource = infinity
previous = invalid_node
visited = False
def populateNodeTable():
nodeTable = []
f = open("twoDArray.txt", "r")
for line in f.readlines(): #get number of nodes from file
nodeTable.append(line.split(',')) # Create matrix of weights
numNodes = len(nodeTable) # Count nodes
print numNodes
#for all nodes in text file, set visited to false, distFromSource to infinity & predecessor to none
**for i in numNodes:
nodeTable.append(Node(i))**
#nodeTable.append(Node())
nodeTable[startNode].distFromSource = 0
print nodeTable
if __name__ == "__main__":
populateArray()
populateNodeTable()
當我運行這段代碼,我得到了以下錯誤:
Traceback (most recent call last):
File "2dArray.py", line 63, in <module>
populateNodeTable()
File "2dArray.py", line 18, in populateNodeTable
for i in numNodes:
TypeError: 'int' object is not iterable
我不知道我該怎麼糾正這個錯誤(星號之間的部分) - 我所試圖做的是讀我的文字文件,該文件僅僅是一系列用逗號分隔的整數,和計數該文本文件中的節點數量 然後將爲每個節點分配值Node類
您正在使用相同的列表來存儲您讀入的行和您創建的節點。你甚至沒有使用'split'的結果。爲什麼不在迭代每行時添加節點? – unholysampler 2011-02-23 22:07:50
這不是你如何在Python中定義一個(n可實例化的)類。這就是你如何定義一個具有幾個類變量的假類。 – delnan 2011-02-23 22:12:33
@delnan,這就是當你餵養你的蛇咖啡,而不是鴨子 – 2011-02-23 23:02:25