python - Python字典查找具有复合键属性的值
问题描述
字典有一个自定义类作为键。我想通过使用哈希函数的值而不是对象来搜索键的存在。
下面的代码段打印无、无、无。原因是实例的eq检查。但是,我无法删除 isInstance 检查(解释器失败)
关于如何获得打印 None, object one, object 2 的结果的任何建议?
class person:
def __init__(self, name, age):
self.name = name
self.age = age
def __hash__(self):
return self.age
def __eq__(self, other):
return isinstance(other,person) and other.age == self.age
def __str__(self):
return 'name: ' + self.name + ' age: ' + self.age
class find:
def run(age):
d = {obj('hi',10) : 'one', obj('bye',20) : 'two'}
item = d.get(age, None)
print(item)
one = person('one',1)
two = person('two', 2)
d = {one : 'one', two: 'two'}
print(d.get(0, None))
print(d.get(1, None))
print(d.get(2, None))
解决方案
事实上,python 允许在同一个字典中使用相同的哈希值。
你可以试试
d = {one : 'one', two: 'two', 1: 'one'}
这不会显示错误。
如果你想知道为什么。您应该搜索python如何使用哈希表实现dict。
在你的代码中。您可以通过以下方式获得您的价值:
d[one]
或者
d.get(one, None)
推荐阅读
- json - MariaDB 10.6.4 JSON_TABLE 函数
- angular - 当其值为 10 时,字符串属性在 UI 中未反映正确的值
- javascript - 如何使用 watchPosition (js) 获得正确的经纬度
- mysql - 具有相关数据(带连接)的行的限制和偏移(分页)
- vim - 在 Vim 中搜索模式并删除具有该模式的单词
- reactjs - React 测试库 - 模拟一个函数
- javascript - 是否可以在不使用当前状态的条件语句的情况下使用状态机?
- python - 基于配置和用户的动态过滤器:PySpark
- html - 我可以为粉红色冥想网站添加哪些设计方面使其看起来更有趣?
- python - 如何在表单中使用 pythonmechanissoup 将文件上传到 ASP.net 站点