【发布时间】:2023-04-01 03:40:01
【问题描述】:
我正在学习 python,这是一个练习,我正在尝试构建图形数据。
class Vertex:
def __init__(self, value):
self.value = value
self.edges = {}
def add_edge(self, vertex, weight = 0):
self.edges[vertex] = weight
def get_edges(self):
return list(self.edges.keys())
class Graph:
def __init__(self, directed = False):
self.graph_dict = {}
self.directed = directed
def add_vertex(self, vertex):
self.graph_dict[vertex.value] = vertex
def add_edge(self, from_vertex, to_vertex, weight = 0):
self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
if not self.directed:
self.graph_dict[to_vertex.value].add_edge(from_vertex.value, weight)
在add_edge
方法的图形类中,我发现以下代码很复杂,我不明白它是如何工作的。
self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
【问题讨论】:
-
你可以把它写成行:从字典
vertex = self.graph_dict[from_vertex.value]
中获取一些顶点,然后在这个顶点上添加新边vertex.add_edge(to_vertex.value, weight)
标签:
python
data-structures
graph
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:图数据结构的python类包含添加边缘方法我发现它很难理解 - Python技术站