我有一个使用自定义哈希方法的类.
class Test(object):
def __init__(self, key, value):
self.key = key # key is unique
self.value = value
def __hash__(self):
# 'value' is unhashable, so return the hash of 'key'
return hash(self.key)
Run Code Online (Sandbox Code Playgroud)
我创建了set
这个类的使用对象.
t0, t1, t2 = Test(0, 10), Test(1, 5), Test(2, 10)
s = set([t0, t1, t2])
Run Code Online (Sandbox Code Playgroud)
现在,有没有办法从s
使用中找到对象key
?即我想做:
find_using_key(s, 1) # should return [t1]
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过迭代集合中的项目来做到这一点,但我觉得应该有一个O(1)方法来做到这一点,因为key
有效地确定了"位置" set
.
...因为键有效地确定了集合中的"位置"
那不是真的.具有相同的两个元素key
可以在集合中共存:
>>> t0, t1 = Test(1,1), Test(1,2)
>>> len(set((t0,t1)))
2
Run Code Online (Sandbox Code Playgroud)
哈希值不定义相等性.这也是不可能的,因为你可以有哈希冲突.
至于你的问题:不要使用set
.它由一个带有操作insert和find的抽象接口定义.它不提供您想要的操作.潜在的底层实现是否理论上可以支持您想要的操作并不是真正相关的.而是使用a dict
,并将键与实例相关联.