为什么Python中List的容量在删除元素后减少到10而不是8?

2024-06-17 13:17:33 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么容量从8降到了10?在

#Do not remove the below import statement
import sys
'''This function provides the capacity, size and space left in the list.
You can invoke it to get the details of the list'''

def list_details(lst):

    #Number of elements that can be stored in the list
    print("Capacity:", (sys.getsizeof(lst)-36)//4)

    #Number of elements in the list
    print("Size:", len(lst))

    #Number of elements that can be accommodated in the space left
    print("Space Left:", ((sys.getsizeof(lst)-36) - len(lst*4))//4)

    #formula changes based on the system architecture
    #(size-36)/4 for 32 bit machines and
    #(size-64)/8 for 64 bit machines
    # 36, 64 - size of an empty list based on machine
    # 4, 8 - size of a single element in the list based on machine

marias_lst=[]
print("Empty list created!!!")
print("List details:")
list_details(marias_lst)
for i in range(0,10):
    marias_lst.append(1)

print("List details After adding 10 elements :")
list_details(marias_lst)
for i in range(0,3):
    marias_lst.remove(1)

print("List details after removing 3 elements:")
list_details(marias_lst)

我使用上面的程序来理解python中列表的增长是如何发生的。我的疑问是什么时候 我加1个元素,容量增加到4个 我增加5个元素,容量增加到8个 我加上10个元素,容量增加到16个

现在,当我在添加10个元素之后删除3个元素时,我得到以下输出

^{pr2}$

为什么容量不是8,空间是1?在

**编辑1** 在32位机器python解释器上,我们的列表增长如下所示

>>> import sys
>>> sys.getsizeof([])
36
>>> sys.getsizeof([1])
40
>>> lst = []
>>> lst.append(1)
>>> sys.getsizeof(lst)
52

Tags: ofthein元素forsizesyselements
1条回答
网友
1楼 · 发布于 2024-06-17 13:17:33

没有理由期望容量是8。如果在新的Python版本或其他实现(如PyPy)上运行它,也没有理由期望容量再次达到10。事实上,它恰好是10,这是一个实现细节,您不应该依赖,也不希望保持不变。在

容量刚好是10,因为remove-减少到少于容量一半的元素会触发收缩,并且(目前,on modern CPython)resize例程将过度分配计算为

new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

newsize为7时,这将产生3个元素的过度分配,新容量为10。在

相关问题 更多 >