1
我是新來的Python,我想製作Dijkstra的算法,我在開始時遇到問題。添加到列表中的對象最終添加到所有列表對象
我有一個頂點和邊對象:
class Vertex:
minDistance = float('inf')
previousVertex = None
edges = []
id = None
name = None
def __init__(self, id, name):
self.id = id
self.name = name
class Edge:
source = None
target = None
weight = None
def __init__(self, source, target, weight):
self.source = source
self.target = target
self.weight = weight
我要帶一個頂點和他的財產邊緣添加每次啓動它的邊緣。這樣做對每一個頂點,我有:
vertices = []
def createGraph(self, vertices, edgesToVertices):
self.vertices = vertices[:]
for x in vertices:
for edge in edgesToVertices:
if edge.source is x.id:
x.edges.append(edge)
問題是,當我追加的最後一行,邊緣被添加到列表中的所有頂點。 有人可以請解釋我做錯了什麼,爲什麼?
您應該使用'=='而不是'is'來測試相等性。我懷疑這是你的問題的根源,儘管 –
刪除緊接在class class下面的三行:如果你想擁有默認屬性,把它們作爲'__init__'的默認參數。 –
'Vertex'也一樣。我認爲問題是,所有的頂點共享一個列表'邊緣' –