查找整数近邻的字典近邻、整数、字典

由网友(情伤ㄥ离人语づ)分享简介:我有一个字典这需要整数键:I have a dict that takes integer keys:a = {}a[1] = 100a[55] = 101a[127] = 102我希望能够询问什么时候采取近邻:I would like to be able to take the nearest neig...

我有一个字典这需要整数键:

I have a dict that takes integer keys:

a = {}
a[1] = 100
a[55] = 101
a[127] = 102

我希望能够询问什么时候采取近邻:

I would like to be able to take the nearest neighbour when asking :

a[20] # should return a[1] = 100
a[58] # should return a[55] = 101
a[167] # should return a[127] = 102

是否有这样做的Python的方式?(我想这可以通过循环上的所有字典来完成,但是这可能不是最优雅的解决方案?)

Is there a pythonic way of doing this? (I imagine this can be done by looping on all dict, but that's probably not the most elegant solution?)

双指数同样的问题的(整数和):

 b[90, 1] = 100, b[90, 55] = 101, b[90, 127] = 102
 b[70, 1] = 40, b[70, 45] = 41, b[70, 107] = 42

我希望能够得到的 B [73,40] = B [70,45] = 41 ,即最近neighboor在2D平面上。的

推荐答案

也有类似这样:

class CustomDict(dict):
    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            closest_key = min(self.keys(), key=lambda x: abs(x - key))
            return dict.__getitem__(self, closest_key)

或者这样:

class CustomDict(dict):
    def __getitem__(self, key):
        if key in self:
            return dict.__getitem__(self, key)
        else:
            closest_key = min(self.keys(), key=lambda x: abs(x - key))
            return dict.__getitem__(self, closest_key)

这两个给出了这样的结果:

Both gives this result:

a = CustomDict()
a[1] = 100
a[55] = 101
a[127] = 102

print a[20] # prints 100
print a[58] # prints 101
print a[167] # prints 102

和为双指数版本:

class CustomDoubleDict(dict):
    def __getitem__(self, key):
        if key in self:
            return dict.__getitem__(self, key)
        else:
            closest_key = min(self.keys(), key=lambda c: (c[0] - key[0]) ** 2 + (c[1] - key[1]) ** 2)
            return dict.__getitem__(self, closest_key)


b = CustomDoubleDict()
b[90, 1] = 100
b[90, 55] = 101
b[90, 127] = 102
b[70, 1] = 40
b[70, 45] = 41
b[70, 107] = 42

print b[73, 40]  # prints 41
print b[70, 45]  # prints 41
阅读全文

相关推荐

最新文章