python获取字典长度_如何知道数组和字典等python对象的字节大小? -简单的方法...

使用此食谱,从这里获取:

[HTTP://code.active state.com/recipes/577504-compute-memory-footprint-of-按-object-安定-ITS-cont/]

from __future__ import print_function

from sys import getsizeof, stderr

from itertools import chain

from collections import deque

try:

from reprlib import repr

except ImportError:

pass

def total_size(o, handlers={}, verbose=False):

""" Returns the approximate memory footprint an object and all of its contents.

Automatically finds the contents of the following builtin containers and

their subclasses: tuple, list, deque, dict, set and frozenset.

To search other containers, add handlers to iterate over their contents:

handlers = {SomeContainerClass: iter,

OtherContainerClass: OtherContainerClass.get_elements}

"""

dict_handler = lambda d: chain.from_iterable(d.items())

all_handlers = {tuple: iter,

list: iter,

deque: iter,

dict: dict_handler,

set: iter,

frozenset: iter,

}

all_handlers.update(handlers) # user handlers take precedence

seen = set() # track which object id's have already been seen

default_size = getsizeof(0) # estimate sizeof object without __sizeof__

def sizeof(o):

if id(o) in seen: # do not double count the same object

return 0

seen.add(id(o))

s = getsizeof(o, default_size)

if verbose:

print(s, type(o), repr(o), file=stderr)

for typ, handler in all_handlers.items():

if isinstance(o, typ):

s += sum(map(sizeof, handler(o)))

break

return s

return sizeof(o)

##### Example call #####

if __name__ == '__main__':

d = dict(a=1, b=2, c=3, d=[4,5,6,7], e='a string of chars')

print(total_size(d, verbose=True))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值