您怎么知道两个对象相等或不相等?
这很重要。如果我们写,
d[3] = 0
d[3] = 99
d[1] = 5
d[2] = 104
然后,99
应该代替0
。这是因为3 == 3
。但是,104
不应该替换5
,因为1 != 2
。但是,计算机如何知道字典键是否彼此相等?
考虑以下代码:
x = "apple"
y = "apple"
print(x == y)
输出为True
。但是计算机如何知道两个字符串相等?好吧,它将字符串转换为数字,然后比较数字是否相等。见下文:
x = "apple"
y = "apple"
x_number = hash(x)
y_number = hash(y)
print(x_number)
print(y_number)
输出为:
1505705734
1505705734
假设您编写了自己的课程:
class XYCoodinate:
def __init__(self,x,y):
self.x = x
self.y = y
计算机如何知道两个实例是否相等?除非您告诉计算机,否则计算机不知道两个XYCoodinates
相等意味着什么。
xy1 = XYCoodinate(1,2)
xy2 = XYCoodinate(1,2)
print(xy1 == xy2)
尽管两个XYCoodinate
看起来与人类相当,但相等性测试的输出为False
。老实说,计算机不知道该怎么办。因此,默认行为如下:
def __eq__(lhs,rhs):
# `lhs`...........`left-hand-side`
# `rhs`...........`right-hand-side`
if `lhs` and `rhs` are two different labels for the same memory "hotel room"
# if a hotel room contains 5 it contains 5,not both 2 and 5.
# if you have two different names for the same hotel room,they must be equal
return True
if `lhs` and `rhs` are two different memory "hotel room" numbers:
# the hotel rooms might contain two copies the same data,the hotel rooms might not
# However,unless it's something simply like an integer,# the computer doesn't know how to tell if they are equal or not.
计算机知道如何对整数和整数元组进行哈希处理,所以我们可以这样做:
class XYCoordinate:
def __init__(self,y):
self.x = x
self.y = y
def __hash__(self):
return hash(tuple([self.x,self.y]))
def __eq__(lhs,rhs):
return hash(lhs) == hash(rhs)
xy1 = XYCoordinate(1,2)
xy2 = XYCoordinate(1,2)
print(hash(xy1))
print(hash(xy2))
print(xy1 == xy2)
输出为:
994727857
994727857
True
当您将某些内容用作字典键时,字典将使用哈希值。 dct[xy1] = "apple"
与dct[hash(xy1)] = "apple"
几乎
如果具有哈希值994727857
的对象 更改 ,该怎么办?那将非常非常糟糕。
XYCoordinate类:
def init (自身,x,y):
self.x = x
self.y = y
def 哈希(自己):
返回hash(tuple([self.x,self.y]))
def eq (lhs,rhs):
返回hash(lhs)== hash(rhs)
def str (自己):
返回str(tuple([self.x,self.y]))
def repr (自己):
返回str(self)
d = dict()
xy1 = XYCoordinate(1,2)
xy2 = XYCoordinate(3,4)
d[xy1] = "apple"
d[xy2] = "banana"
print(d)
# {(1,2): 'apple',(3,4): 'banana'}
# change `xy2` to be the "same" as xy1
xy2.x = xy1.x
xy2.y = xy1.y
print(xy2) # prints (1,2)
# d[(1,2)] = "orange"
d[xy2] = "orange"
print(d)
# {(1,2): 'orange',(1,2): 'banana'}
看完以上内容,希望您问自己:“到底发生了什么?最后的字典{(1,2): 'banana'}
怎么样?”
用作字典键的事物应该 从不 发生变化。
d[key] = 5
# key does not change
# key does not change
# [... a long time later]
# key does not change
# key does not change
d[key] = 99
由于尝试将字典(token
)用作另一本字典的键而出错。
key_ab = {1:"apple" 2:"banana"}
key_cd = {1:"cantaloupe",2:"date" }
d = dict()
d[key_ab] = 4
d[key_cd] = 99
# key not supposed to change!
key_cd = {1:"apple",2:"banana" }
d[key_cd] = 104
无论用作字典键,请确保它们为 恒定 。数字4永远不变。您可以通过在门上写上“ {x
”来更改酒店房间中的号码,但不能更改号码4。
同样,您可以更改哪个字符串留在哪个酒店房间,但是在python中,字符串“ apple”将永远是“ apple”。
您可以将整数,字符串,整数元组,字符串元组,frozensets和其他一些内容用于字典 键 。 值 应该可以更改,但不能更改 键 。您也可以使用定义了__hash__
方法的任何东西,但是只有当您可以超级特殊地确定对象在调用hash
之后永远不会改变时,才能这样做。第一次。
本文链接:https://www.f2er.com/3159796.html