我有一個自定義哈希方法的類。Python:從基於密鑰的集中獲取項目
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)
我使用此類的對象製作set
。
t0, t1, t2 = Test(0, 10), Test(1, 5), Test(2, 10)
s = set([t0, t1, t2])
現在,有沒有辦法使用key
找到從s
對象?即我想做的事:
find_using_key(s, 1) # should return [t1]
我知道我可以通過遍歷集合中的項目做到這一點,但我覺得應該有一個O(1)方法來做到這一點,因爲key
有效地確定了「位置'在set
。
你能解釋一下爲什麼你不能使用字典? – DSM