所以我有一个由一系列点组成的正方形。每一点都有一个相应的值。
我想要做的是建立一个这样的字典:
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
square = {}
for x in range(0, 5):
for y in range(0, 5):
point = Point(x,y)
square[point] = None
但是,如果我稍后创建一个新的点对象并尝试使用该点的键访问字典的值,则它不起作用..
>> square[Point(2,2)]
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
square[Point(2,2)]
KeyError: <__main__.Point instance at 0x02E6C378>
我猜这是因为python不认为具有相同属性的两个对象是同一个对象?有没有办法解决?感谢
答案 0 :(得分:12)
定义Point.__hash__()
和Point.__eq__()
,以便在dicts中正确比较它们。
虽然您正在考虑,但请考虑定义Point.__repr__()
,以便您对Point
个对象进行体面的展示。
答案 1 :(得分:5)
是的,在Point类上定义__eq__
和__hash__
方法。
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def __eq__(self, other):
return self._x == other._x and self._y == other._y
def __hash__(self):
#This one's up to you, but it should be unique. Something like x*1000000 + y.
答案 2 :(得分:2)
任何不使用元组的原因:
>>> s={}
>>> s[1,2]=5
>>> s
{(1, 2): 5}
>>> s[1,2]
5
答案 3 :(得分:2)
步骤:实现自定义键类并覆盖哈希和相等函数。
e.g。
class CustomDictKey(object):
def __init__(self,
param1,
param2):
self._param1 = param1
self._param2 = param2
# overriding hash and equality function does the trick
def __hash__(self):
return hash((self._param1,
self._param2))
def __eq__(self, other):
return ( ( self._param1,
self._param2 ) == ( other._param1,
other._param2) )
def __str__(self):
return "param 1: {0} param 2: {1} ".format(self._param1, self._param2)
if name == 'main':
# create custom key
k1 = CustomDictKey(10,5)
k2 = CustomDictKey (2, 4)
dictionary = {}
#insert elements in dictionary with custom key
dictionary[k1] = 10
dictionary[k2] = 20
# access dictionary values with custom keys and print values
print "key: ", k1, "val :", dictionary[k1]
print "key: ", k2, "val :", dictionary[k2]
请参阅文章Using custom class as key in python dictionary 以获取完整的详细信息。