栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

什么是“冻结命令”?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

什么是“冻结命令”?

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 yFalse>>> x == yTrue>>> x == {'a': 1, 'b': 2}True>>> d = {x: 'foo'}>>> d[y]'foo'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669290.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号