什么是“冻结命令”?
- 冻结集是冻结集。
- 冻结列表可能是一个元组。
- 冻结的字典是什么?一个不变的,可哈希的字典。
我猜可能是collections.namedtuple,但是更像是冰冻的字典(半冻结的字典)。是不是
A“frozendict”应该是一个冰冻的字典,它应该有keys,values,get,等,并支持in,for等等。
更新:
*它是:https : //www.python.org/dev/peps/pep-0603
回答:
Python没有内置的Frozendict类型。事实证明,这并不是太有用了(尽管它可能仍然比以前有用frozenset)。
想要这种类型的最常见原因是在记忆函数调用具有未知参数的函数时。存储dict(其中值是可哈希的)的可哈希等效的最常见解决方案是tuple(sorted(kwargs.iteritems()))。
这取决于排序是否有点疯狂。Python无法肯定地承诺排序将在这里产生合理的结果。(但是它不能保证其他任何事情,所以不要过多地出汗。)
您可以轻松地制作某种类似于dict的包装器。它可能看起来像
import collectionsclass 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:
            hash_ = 0
            for pair in self.items():
                hash_ ^= hash(pair)
            self._hash = hash_
        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'
以上是 什么是“冻结命令”? 的全部内容, 来源链接: utcz.com/qa/416378.html




