显然,从字典中删除条目不会触发任何大小调整。
这可以从以下内容中看出:
# Drastic example, nobody does such
# things with dicts FWIK
from sys import getsizeof
d = {i:i for i in range(100)}
print(getsizeof(d)) # 4704
for i in range(100):
del d[i] # similarly with pop
print(getsizeof(d)) # 4704
根据我所发现的SO上的一个问题,set
的行为方式类似,这是符合字典的预期的。
另一方面,当新大小变为已分配大小的一半时,list
会调整大小;这在list_resize
注释中有说明:
/* Bypass realloc() when a previous overallocation is large enough
to accommodate the newsize. If the newsize falls lower than half
the allocated size, then proceed with the realloc() to shrink the list.
*/
为什么字典(以及间接地,集合)不采用类似的技巧,而是等待插入新条目?所描述的行为适用于Python 2.7和3.x。
d.clear()
会重新调整大小。 - Jean-François Fabre