如何用for循环在Python中填充图的元组边?解决添加边报错问题
解决方法
1. append报错的原因
你的graph是自定义Graph类的实例,不是Python原生列表,所以没有append方法,直接调用必然报错。要添加边,要么在初始化时批量生成边集合,要么给Graph类添加实例方法支持动态添加。
2. 用for循环初始化填充图
如果想在初始化Graph时用for循环生成边,可以先定义所有边的原始数据,再循环转换成Edge对象后传入:
from collections import namedtuple Edge = namedtuple('Edge', 'start, end, cost') def add_edge(start, end, cost): return Edge(start, end, int(cost)) # 把cost转为整数,避免字符串类型干扰算法计算 # 定义所有边的原始数据 raw_edges = [ ("a", "b", 2),("a", "c", 5), ("a", "d", 2),("b", "c", 3), ("b", "e", 1),("c", "e", 1), ("c", "h", 1),("c", "f", 1), ("c", "d", 3),("d", "g", 2), ("e", "i", 7),("f", "h", 3), ("f", "g", 2),("h", "i", 1), ("i", "j", 4) # 新增的边 ] # 用for循环生成Edge对象列表 edges = [] for start, end, cost in raw_edges: edges.append(add_edge(start, end, cost)) # 初始化Graph graph = Graph(edges)
也可以用列表推导式简化:
edges = [add_edge(s, e, c) for s, e, c in raw_edges] graph = Graph(edges)
3. 动态添加边(给Graph类扩展方法)
如果需要在初始化后动态添加边,需要给Graph类添加一个实例方法:
class Graph: def __init__(self, edges=None): # 初始化边集合,默认空列表 self.edges = edges if edges is not None else [] # 新增实例方法,用于添加单条边 def add_edge(self, start, end, cost): edge = Edge(start, end, int(cost)) self.edges.append(edge)
之后就可以用for循环批量添加边:
# 初始化空图 graph = Graph() # 待添加的边列表 new_edges = [ ("i", "j", 4), ("j", "k", 3), ("k", "l", 2) ] # 用for循环批量添加 for start, end, cost in new_edges: graph.add_edge(start, end, cost)
关键注意点
- 之前你尝试添加的
("i", "j", "4")中,cost是字符串类型,Dijkstra算法需要数值类型(整数/浮点数)进行计算,必须转换为数值类型,避免后续计算报错。 - 确保你的
Graph类内部通过self.edges或类似属性存储边集合,这样添加的边才能被算法正确读取。
内容的提问来源于stack exchange,提问作者Saturday7
相关产品推荐
相关产品推荐

