python - 使用自定义对象查询 Python 字典键

标签 python dictionary

考虑一个字典,其中的键是使用以下类的对象创建的:

class Point( object ):

    def __init__( self, x, y ):
        self.x = x
        self.y = y

    def __eq__( self, other ):
        return self.x == other.x

    def __hash__( self ):
        return self.x.__hash__()

    def __ne__( self, other ):
        return self.x != other.x

>>> a = Point(1,1)
>>> b = Point(0, 2)
>>> dct = {}
>>> dct[a] = 15
>>> dct[b] = 16
>>> dct[a]
15
>>> c = Point(1,None)
>>> dct[c]
15

发生这种情况是因为 ca 共享相同的散列且相等。是否有 O(1) 方法来实现给定 c 返回 a 的函数(与下面的 O(n) 实现相反?):

def getKey( dct, key ):
    for k in dct:
        if k == key:
            return k
    return None

最佳答案

你的函数总是返回 Nonekey,所以我不明白你的意思...

根据复杂度,假设你至少需要 O(log(n)), 例如,如果 dct 是我认为的字典,那么:

def getKey( dct, key ):
    if dct.has_key(key):
        return key
    return None

如果你想返回它的值,那么只需使用:dct.get(key, None)

关于python - 使用自定义对象查询 Python 字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842152/

相关文章:

基于 python 的 Dockerfile 抛出 locale.Error : unsupported locale setting

python - 从map()返回不同的变量

python字典错误AttributeError : 'list' object has no attribute 'item'

python - 将嵌套字典转换为Python中的列表?

python - Pandas 数据框列上的子字符串

python - python中多边形绘图的亚像素精度?

Python 内部中断函数

Python:用于提取在括号之间找到的部分 URL 的正则表达式

带有重复/重复元素的 Python "set"

java - 并发 HashMap 删除复杂值