2013-02-22 86 views
1

在以下圖形實現中,v, w = e分配的作用是什麼?它如何工作?我認爲我們不允許做這樣的不對稱任務。在Python圖形中添加邊緣(初學者)

class Graph(dict): 
    def __init__(self, vs=[], es=[]): 
     """create a new graph. (vs) is a list of vertices; 
     (es) is a list of edges.""" 
     for v in vs: 
      self.add_vertex(v) 

     for e in es: 
      self.add_edge(e) 

    def add_vertex(self, v): 
     """add (v) to the graph""" 
     self[v] = {} 

    def add_edge(self, e): 
     """add (e) to the graph by adding an entry in both directions. 

     If there is already an edge connecting these Vertices, the 
     new edge replaces it. 
     """ 
     v, w = e 
     self[v][w] = e 
     self[w][v] = e 
+0

它被稱爲「解包」 - 例如'a,b = [1,2]' – 2013-02-22 21:07:51

回答

3

它的工作方式是這樣的: é實際上是一個元組,由兩個元素。陳述v, w = e等於將e的第一個元素分配給v,將第二個元素分配給w。

作爲示範,請檢查下面的Python控制檯輸出:

>>> e = (1, 2) 
>>> u, v = e 
>>> u 
1 
>>> v 
2 

。希望清除它有點。

0

這是因爲Allan Downey(book)想讓你在他的書的下一頁中解開包裝。

在這裏,他寫道:

class Edge(tuple): 
    def __new__(cls, *vs): 
     return tuple.__new__(cls, vs) 

    def __repr__(self): 
     return 'Edge(%s, %s)' % (repr(self[0]), repr(self[1])) 

    __str__ = __repr__ 

...所以它成爲明確的,它是一個元組。