在Python图中添加边(初学者)
在下面这个图的实现中,v, w = e
这个赋值到底是干嘛的,它是怎么工作的?我以为我们不允许这样不对称的赋值呢。
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
2 个回答
0
这是因为 Allan Downey(他的书)想在书的下一页给你展示如何拆解(unpacking)。
在这里他写道:
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__
...所以这就明确表示它是一个元组(tuple)。
4
这个东西的工作原理是这样的:
e 实际上是一个元组,里面有两个元素。写 v, w = e
就相当于把 e 的第一个元素赋值给 v,把第二个元素赋值给 w。
为了演示一下,可以看看下面的 Python 控制台输出:
>>> e = (1, 2)
>>> u, v = e
>>> u
1
>>> v
2
希望这样能让你更明白一些。