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

python中的OrderedDict vs Dict

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

python中的OrderedDict vs Dict

我认为大小的问题是由于

__sizeof__
在Python
2.X的实现中
OrderedDict
没有定义方法的事实,所以它只是退回到dict的
__sizeof__
方法。

为了在这里证明这一点,我在这里创建了一个

A
扩展的类,
list
并且还添加了一个额外的方法
foo
来检查是否影响大小。

class A(list):    def __getitem__(self, k):        return list.__getitem__(self, k)    def foo(self):        print 'abcde'>>> a = A(range(1000))>>> b = list(range(1000))

但仍返回相同的大小

sys.getsizeof

>>> sys.getsizeof(a), sys.getsizeof(b)(9120, 9120)

当然

A
会很慢,因为它的方法在Python中运行,而list的方法将在纯C中运行。

>>> %%timeit... for _ in xrange(1000):...     a[_]... 1000 loops, best of 3: 449 µs per loop>>> %%timeitfor _ in xrange(1000):    b[_]... 10000 loops, best of 3: 52 µs per loop

这似乎在Python 3中已得到修复,该Python
3中现在有一个定义明确的

__sizeof__
方法:

def __sizeof__(self):    sizeof = _sys.getsizeof    n = len(self) + 1 # number of links including root    size = sizeof(self.__dict__) # instance dictionary    size += sizeof(self.__map) * 2          # internal dict and inherited dict    size += sizeof(self.__hardroot) * n     # link objects    size += sizeof(self.__root) * n         # proxy objects    return size


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

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

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