sys.getsizeof(list)返回的值小于其元素的总和 [英] sys.getsizeof(list) returns less than the sum of its elements

查看:86
本文介绍了sys.getsizeof(list)返回的值小于其元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇-为什么 sys.getsizeof 调用返回比列表元素总和还小的数字吗?

I'm curious - why does the sys.getsizeof call return a smaller number for a list than the sum of its elements?

import sys
lst = ["abcde", "fghij", "klmno", "pqrst", "uvwxy"]
print("Element sizes:", [sys.getsizeof(el) for el in lst])
print("Sum of sizes: ", sum([sys.getsizeof(el) for el in lst]))
print("Size of list: ", sys.getsizeof(lst))

上面的照片

Element sizes: [42, 42, 42, 42, 42]
Sum of sizes:  210
Size of list:  112

怎么来?

推荐答案

您正在获取实际列表对象的大小.当列表对象存储指向对象的指针时,其内存大小必然不同于(小于)其元素的总和.

You are getting the size of the actual list object. As the list object stores pointers to objects its memory size is bound to be different (and lower) than the sum of its elements.

比喻,这就像用C获取指针数组的大小.

By analogy, it’s like getting the size of an array of pointers in C.

这篇关于sys.getsizeof(list)返回的值小于其元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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