python - 如何确定 KeyError 的来源?

标签 python

我正在使用邻接列表在 Python 3.x 中编写(有向)图的简单实现。为了删除图形的边缘,我正在查看一个如下所示的函数:

class Graph(object):

    def __init__(self):
        self.vertices = {}

    def add_vertex(self, x):
        """ Adds x to the graph, if it doesn't exist """
        if x not in self.vertices:
            self.vertices[x] = set()
        else:
            print("Error: vertex {} already in graph!".format(x))                

    def add_edge(self, x, y):
        """ Adds the edge from x to y, if it doesn't exist """
        try: 
            if y not in self.vertices[x]:
                self.vertices[x].add(y)
            else:
                print("Error: edge already exists!")
        except KeyError:
            print("Error: vertex {} not found!".format(x))

    def remove_edge(self, x, y):
        """ Removes the edge from x to y, if it exists """

        try:
           self.vertices[x].remove(y)
        except KeyError:
           # QUESTION: which part of the try block caused the KeyError?
           print("Error: vertex not found!")

我的问题是,因为我使用的是集合字典,所以两者都会引发 KeyError

self.vertices[x].remove(y)

如果我想打印一条错误消息,指示这两个顶点之一(xy)不存在,是否有办法确定哪一部分该行的哪一行引发了错误?或者我是否必须再次检查并根据(重复)检查得出错误消息?

(注意:我认识到上面的代码中存在一些逻辑错误 - 例如,add_edge 需要检查 x 和 y 是否都存在。)

最佳答案

所以首先检查图中是否存在名为 x 的节点,如果存在则检查是否存在从 x 到 y 的边

def remove_edge(self, x, y):
    """ Removes the edge from x to y, if it exists """    
    if x in self.vertices:
        if y in self.vertices[x]:
            self.vertices[x].remove(y)
        else:
            print("There is no edge from x to y")
    else:
         print("There is no node x present in the graph")

如果你真的想知道的话可以根据try catch

def remove_edge(self, x, y):
    """ Removes the edge from x to y, if it exists """

    try:
       self.vertices[x]
    except KeyError:
       print("Error: vertex x not found!")

    try:
       self.vertices[x].remove(y)
    except KeyError:
       print("Error: vertex y not found!")

关于python - 如何确定 KeyError 的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45124723/

相关文章:

python - Celery 从 Django 模块内部记录到文件

python 分配给自身内部的对象

python - 如何杀死uwsgi的所有实例

python - 理解 python 中的点符号

python - 尝试在 python 中进行线性插值

python - 预处理扫描不良的手写数字

python - 如何在网站上抓取嵌入的整数

python - Windows 客户端和 Linux 服务器之间的通信

python - 寻找更优雅的解决方案

python - 展平 pandas 数据框的嵌套 Json?