You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建邻接列表图时出现KeyError错误,求排查思路

解决邻接列表构建时的KeyError问题

我用pandas导入Excel数据,计划构建邻接列表形式的图,数据导入过程正常,但调用自定义的add_edge函数时,持续出现KeyError错误。

原代码如下:

import pandas as pd

df = pd.read_excel(r'my_file_path.xlsx')

class Graph:
    def __init__(self, nodes): 
        self.nodes = nodes  # 图中所有节点
        self.adj_list = {}  # 邻接列表

        # 遍历节点,用集合去重后作为邻接列表的键
        self.adj_list = {node: set() for node in self.nodes}
   
   
    def add_edge(self, node_1, node_2, weight):
        # 向node_1的邻接列表添加node_2和权重
        self.adj_list[node_1].add((node_2, weight))
        # 向node_2的邻接列表添加node_1和权重
        self.adj_list[node_2].add((node_1, weight))

    # 格式化打印图
    def print_graph(self):
        for node in self.nodes:
            print(node, " :", self.adj_list[node])



nodes = []

for index, row in df.iterrows():
    station_a = row['Station A']
    nodes.append(station_a)


graph = Graph(nodes)

for index, row in df.iterrows():
  
    station_a = row['Station A']
    station_b = row['Station B']
    weight = row['Weight']
    graph.add_edge(station_a, station_b, weight)

graph.print_graph()

错误原因

KeyError的核心问题是:你收集节点时只提取了Station A列的站点,导致Graph初始化后,adj_list的键仅包含这些站点;但构建边时需要访问Station B的站点,这些站点不在adj_list的键集合中,因此触发KeyError。

修复方案

  1. 收集所有节点:同时包含Station A和Station B的所有站点,并用集合去重
  2. 优化节点收集逻辑:利用pandas的列操作替代循环,更高效简洁

修正后的代码:

import pandas as pd

df = pd.read_excel(r'my_file_path.xlsx')

class Graph:
    def __init__(self, nodes): 
        self.nodes = nodes  
        self.adj_list = {node: set() for node in self.nodes}
   
    def add_edge(self, node_1, node_2, weight):
        self.adj_list[node_1].add((node_2, weight))
        self.adj_list[node_2].add((node_1, weight))

    def print_graph(self):
        for node in self.nodes:
            print(node, " :", self.adj_list[node])

# 合并Station A和Station B列,去重后转为列表作为所有节点
all_stations = pd.concat([df['Station A'], df['Station B']]).unique().tolist()

graph = Graph(all_stations)

# 遍历所有行添加边
for _, row in df.iterrows():
    graph.add_edge(row['Station A'], row['Station B'], row['Weight'])

graph.print_graph()

额外优化建议

  • 若担心数据异常,可在add_edge方法中添加节点存在性判断,但只要初始化时包含所有节点,该判断可省略
  • 用pd.concat+unique替代循环收集节点,代码更简洁且大数据集下性能更优

内容的提问来源于stack exchange,提问作者caman177

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:25:20