什么是“冻结的”是? [英] What would a "frozen dict" be?

查看:122
本文介绍了什么是“冻结的”是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 一个冻结集是一个frozenset。

  • 冻结列表可能是一个元组。

  • 一个冻结的字体是什么?一个不变的,可哈希的话。

我想可能会像 collections.namedtuple 更像一个冷冻的字典(一个半冻的字典)。不是吗?

I guess it could be something like collections.namedtuple, but that is more like a frozen-keys dict (a half-frozen dict). Isn't it?

frozendict应该是一个冻结的字典,它应该有 get 等,并支持中的 for 等。

A "frozendict" should be a frozen dictionary, it should have keys, values, get, etc., and support in, for, etc.

推荐答案

Python没有内置frozendict类型。事实证明,这并不常用(尽管它可能比 frozenset 更有用)。

Python doesn't have a builtin frozendict type. It turns out this wouldn't be useful too often (though it would still probably be useful more often than frozenset is).

想要这样一种类型的最常见的原因是在为具有未知参数的函数记录函数调用时。存储一个可以等同于一个dict的值的最常见的解决方案就是这样一个类似于$ code> tuple(sorted(kwargs.iteritems()))

The most common reason to want such a type is when memoizing function calls for functions with unknown arguments. The most common solution to store a hashable equivalent of a dict (where the values are hashable) is something like tuple(sorted(kwargs.iteritems())).

这取决于排序不是有点疯狂。 Python不能肯定地承诺排序将在这里产生一些合理的东西。 (但是它不能承诺太多,所以不要太多汗。)

This depends on the sorting not being a bit insane. Python cannot positively promise sorting will result in something reasonable here. (But it can't promise much else, so don't sweat it too much.)

你可以很容易做一些类似于dict的包装器。它可能看起来像

You could easily enough make some sort of wrapper that works much like a dict. It might look something like

import collections

class FrozenDict(collections.Mapping):
    """Don't forget the docstrings!!"""

    def __init__(self, *args, **kwargs):
        self._d = dict(*args, **kwargs)
        self._hash = None

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

    def __getitem__(self, key):
        return self._d[key]

    def __hash__(self):
        # It would have been simpler and maybe more obvious to 
        # use hash(tuple(sorted(self._d.iteritems()))) from this discussion
        # so far, but this solution is O(n). I don't know what kind of 
        # n we are going to run into, but sometimes it's hard to resist the 
        # urge to optimize when it will gain improved algorithmic performance.
        if self._hash is None:
            self._hash = 0
            for pair in self.iteritems():
                self._hash ^= hash(pair)
        return self._hash

应该很棒:

>>> x = FrozenDict(a=1, b=2)
>>> y = FrozenDict(a=1, b=2)
>>> x is y
False
>>> x == y
True
>>> x == {'a': 1, 'b': 2}
True
>>> d = {x: 'foo'}
>>> d[y]
'foo'

这篇关于什么是“冻结的”是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆