1

我想做一个 Python 字典。我希望像 0.25、0.30、0.35 这样的值成为这个字典中的键。问题是我的值是 0.264、0.313、0.367。我希望这些值能够访问键,例如,我希望从 0.25(含)到 0.30(不含)的每个值都可以访问键 0.25 下的值。任何想法如何做到这一点?我想我以前以某种方式这样做过,但我现在没有想法。提前致谢。

4

2 回答 2

8

创建一个dict带有adjusted __getitem__, __setitem__, __delitem__, __contains__, get(),pop()update()方法的子类:

class RoundingDict(dict):
    def _round(self, key):
        return int(key * 20) / 20.0

    def __contains__(self, key):
        return super(RoundingDict, self).__contains__(self._round(key))

    def __getitem__(self, key):
        return super(RoundingDict, self).__getitem__(self._round(key))

    def __setitem__(self, key, value):
        super(RoundingDict, self).__setitem__(self._round(key), value)

    def __delitem__(self, key):
        super(RoundingDict, self).__delitem__(self._round(key))

    def get(self, key, default=None):
        return super(RoundingDict, self).get(self._round(key), default)

    def pop(self, key, default=None):
        return super(RoundingDict, self).pop(self._round(key), default)

    def update(self, iterable):
        try:
            super(RoundingDict, self).update({
                self._round(k): v for k, v in iterable.iteritems()})
        except AttributeError:
            super(RoundingDict, self).update((
                (self._round(k), v) for k, v in iterable))

0.05在获取、设置或删除单个键时,以及在使用多个键更新字典时,这会将任何键降到最接近的倍数:

>>> d = RoundingDict()
>>> d[0.346] = 'Foo'
>>> d[0.34]
'Foo'
>>> d[0.30]
'Foo'
>>> d[0.35]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 6, in __getitem__
KeyError: 0.35
>>> d.get(0.34)
'Foo'
>>> d.get(0.35, 'default')
'default'
于 2014-01-23T15:35:42.080 回答
1

您需要的是创建一个自定义字典类,其中该__getitem__方法在调用标准方法之前对值进行四舍五入__getitem__

于 2014-01-23T15:28:20.707 回答