您的问题与mutable and immutable objects的概念密切相关。您问题的确切答案也是特定于实现的。我将为CPython回答它,但请记住,其他实现的行为也有所不同。
在CPython中,一旦创建(分配或使用)了不可变的对象,就会在内存中创建它。每个具有相同值的不可变对象都指向相同的对象(!)。您可以使用id
函数(在CPython中为对象的内存地址)进行检查。
例如:
a = 5 # int's are immutable
d = {5: "five",8: "eight"}
k = 5
# a and k have the same id; they point to the same object!
print(f"id(a) = {id(a)}")
print(f"id(k) = {id(k)}")
print(a in d) # the key a is in dict d
print(d[a]) # the value for key a in dict d
a = (5,) # tuples are also immutable
d = {(5,): "five",(8,): "eight"}
k = (5,)
# a and k have the same id; they point to the same object!
print(f"id(a) = {id(a)}")
print(f"id(k) = {id(k)}")
print(a in d) # the key a is in dict d
print(d[a]) # the value for key a in dict d
即使我将一个构造或计算的不可变对象分配给一个变量,它也与另一个具有相同值的变量是相同的对象(id)。
a1 = 3.14
b1 = 'kgvjkdfsjl'
c1 = (63474236728,)
d1 = 1e10
a2 = 3 + 0.14
b2 = 'kgvj' +'kdfsjl'
c2 = (63474236728,)
d2 = 1e9 * 10
print(all([a1 == a2,b1 == b2,c1 == c2,d1 == d2])) # gives True: the values are all equal
print(all([a1 is a2,b1 is b2,c1 is c2,d1 is d2])) # gives True: the identities are all equal
回到您的问题:
有没有一种有效的方法来查找d中等于k的密钥?
您不必这样做。 CPython会为您解决这个问题。集合中的不可变对象也是如此。
对于任意不可变的可哈希对象是否有通用解决方案?
请注意,不可变对象也可以具有哈希值!默认情况下,所有内置的不可变对象都具有哈希,而可变对象则没有,但是用户可以定义具有自己的哈希函数的类。从而创建可变的和可哈希的对象。
本文链接:https://www.f2er.com/2785278.html