我使用自定义对象作为 python 字典中的键。这些对象有一些默认值hash and eq定义的方法用于默认比较
但在某些功能中我需要使用不同的方式来比较这些对象。
那么有什么方法可以覆盖或传递一个新的比较器来仅针对该特定函数进行这些关键比较。
更新:我的课程具有以下类型的功能(此处我无法编辑hash方法,对其他地方影响很大)
class test(object):
def __init__(self,name,city):
self.name=name
self.city=city
def __eq__(self,other):
hash_equality= (self.name==other.name)
if(not hash_equality):
#check with lower
return (self.name.lower()==other.name.lower())
def __hash__(self):
return self.name.__hash__()
my_dict={}
a=test("a","city1")
my_dict[a]="obj1"
b=test("a","city2")
print b in my_dict #prints true
c=test("A","city1")
print c in my_dict #prints false
print c in my_dict.keys() #prints true
# my_dict[c] throw error
这是正常功能。但在一种特定方法中,我想覆盖/或传递一个新的自定义比较器,其中新的hash代码就像
def __hash__(self):
return self.name.lower().__hash__()
so that c in my_dict
返回真
or my_dict[c] will return "obj1"
抱歉更新了这么多。
就像在排序中一样,我们可以将自定义方法作为比较器传递,有什么方法可以在这里做同样的事情。
实现此目的的唯一方法是使用新的哈希和比较函数创建字典的副本。原因是字典需要使用新的哈希函数重新哈希每个存储的键,以使查找按照您的期望进行。由于您无法向字典提供自定义哈希函数(它始终使用关键对象之一),因此最好的选择可能是将对象包装在使用自定义哈希和比较函数的类型中。
class WrapKey(object):
__init__(self, wrapee):
self._wrapee = wrapee
__hash__(self):
return self._wrapee.name.lower().__hash__()
__eq__(self, other):
return self._wrapee.name == other._wrapee.name
def func(d):
d_copy = dict((WrapKey(key), value) for key, value in d.iteritems())
# d_copy will now ignore case
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)