gpt4 book ai didi

python - 将大数字存储在列表中会更好吗?

转载 作者:IT老高 更新时间:2023-10-28 20:44:13 26 4
gpt4 key购买 nike

在列表中存储大数字是否内存有效?为什么会出现以下情况?

>>> A = 100**100
>>> sys.getsizeof(A)
102
>>> B = [100**100]
>>> sys.getsizeof(B)
40

为什么A和B的大小不相等?

>>> C = [1,100**100]
>>> sys.getsizeof(C)
44
>>> D = [1000**1000, 100**100]
>>> sys.getsizeof(D)
44

为什么C和D的大小相等?

最佳答案

sys.getsizeof() 返回 shallow 大小,即列表对象本身的大小,而不是它包含的对象的大小。

来自 documentation :

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

如果您想计算 deep 大小,可能值得给出 Pympler试一试:

>>> from pympler.asizeof import asizeof
>>> A = 100**100
>>> asizeof(A)
120
>>> B = [100**100]
>>> asizeof(B)
200

因此,在我的计算机上,将 long 放在列表中会增加 80 字节的开销。

关于python - 将大数字存储在列表中会更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27554932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com