我很好奇 - 为什么sys.getsizeof呼叫返回的列表数量少于其元素总和?
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))
Run Code Online (Sandbox Code Playgroud)
以上打印
Element sizes: [42, 42, 42, 42, 42]
Sum of sizes: 210
Size of list: 112
Run Code Online (Sandbox Code Playgroud)
怎么会?
您正在获取实际列表对象的大小。由于列表对象存储指向对象的指针,因此其内存大小必然不同于(且小于)其元素的总和。
\n\n以此类推,\xe2\x80\x99 就像在 C 中获取指针数组的大小一样。
\n