【发布时间】:2015-06-14 00:47:33
【问题描述】:
我正在编写一个 Graph 类来处理游戏中的路径。图有一个字段,映射,它是一个将节点映射到边的字典。在我的一个函数中,我有以下代码:
for key in self.mapping:
connected_edges = self.mapping[key]
在我的程序中,我调用了这段代码,但出现以下错误:
KeyError: <node.Node instance at 0x00000000026F3088>
这怎么可能?我只是遍历字典中的键,那么键怎么可能不在其中呢?为了进行完整性检查,我查看了字典的长度,发现它是 5,即:不是 0。有什么想法吗?谢谢!
我确实为 Node 和 Edge 实现了自己的 eq 和 hash 方法。以下是这些类的部分:
class Node:
"""
A node connects to other nodes via Edges to form a graph
Each node has a unique identifier (ID) so they can be mathematically distinct. Optionally, a node also has an x and
y coordinate.
"""
n_nodes = 0
def __init__(self, x=0, y=0):
"""
Create a node with its own unique identifier.
:param x: x coordinate
:param y: y coordinate
:return: an initialized Node object
"""
Node.n_nodes += 1
self.ID = Node.n_nodes
self.x = x # x position
self.y = y # y position
def __eq__(self, other):
return (self.ID, self.x, self.y) == (other.ID, other.x, other.y)
def __hash__(self):
return hash((self.ID, self.x, self.y))
class Edge:
"""
An edge is a connection between two nodes.
Edges have a unique identifier and a list of two nodes. Optionally, an edge can have a numerical weight. Edges can
also be directed, in which case it is only possible to traverse the edge in one direction, not both.
"""
n_edges = 0
def __init__(self, node1, node2, weight=1, directed=False):
"""
Create an edge with its own unique identifier
:param node1: node at first end of the edge
:param node2: node at second end of the edge
:param weight: numerical weight of the connection between node1 and node2
:param directed: if True, the edge is oriented from node1 to node 2
:return: an initialized Edge object
"""
Edge.n_edges += 1
self.ID = Edge.n_edges
self.weight = weight
self.nodes = frozenset([node1, node2])
self.directed = directed
def __eq__(self, other):
return (self.ID, self.weight, self.nodes, self.directed) == (other.ID, other.weight, other.nodes, other.directed)
def __hash__(self):
return hash((self.ID, self.weight, self.nodes, self.directed))
【问题讨论】:
-
如果您的 Node 对象未正确定义
__hash__和/或__eq__,则可能会发生这种情况。Node是什么?它如何定义__hash__和__eq__? -
顺便说一下,您可能对networkx 库感兴趣。
标签: python dictionary key keyerror