2013-02-22 85 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__ 

...所以它成为明确的,它是一个元组。