如何在Python中查找列表的当前容量
Python中的 List 主要是动态大小数组的实现(如Java中的 ArrayList 或 C++ 中的向量)。列表的容量是指列表在特定时间可以存储的元素数。当我们将元素附加到列表时,如果大小小于容量,它将存储该元素。如果当前容量超出,则列表调整大小并为将来的插入分配额外空间(有关详细信息,请参阅列表在Python中的工作方式)
查找列表的容量和列表中剩余空间的公式:
这里,
空列表的大小意味着分配给空列表的位数,它因系统而异。
列表中一个块的大小也因系统而异。
列表的长度是指被填充的空间块数
示例 1:
# program to find capacity of the list
import sys
l = []
size = sys.getsizeof(l)
print("size of an empty list :", size)
# append an element in the list
l.append(1)
# calculate total size of the list after appending one element
print("Now total size of a list :", sys.getsizeof(l))
# calculate capacity of the list after appending one element
# Considering block size as 8.
capacity = (sys.getsizeof(l)-size)//8
print("capacity of the list is:", capacity)
print("length of the list is :", len(l))
# calculate space left the list after appending one element
spaceleft = ((sys.getsizeof(l)-size)-len(l)*8)//8
print("space left in the list is:", spaceleft)
输出
size of an empty list : 64
Now total size of a list : 96
capacity of the list is: 4
length of the list is: 1
space left in the list is: 3
示例 2:
# program to find capacity of the list
import sys
l = []
size = sys.getsizeof(l)
print("size of an empty list :", size)
# append four element in the list
l.append(1)
l.append(2)
l.append(3)
l.append(4)
# calculate total size of the list after appending four element
print("Now total size of a list :", sys.getsizeof(l))
# calculate capacity of the list after appending four element
c = (sys.getsizeof(l)-size)//8
print("capacity of the list is:", c)
print("length of the list is:", len(l))
# calculate space left the list after appending four element
spaceleft =((sys.getsizeof(l)-size)-len(l)*8)//8
print("space left in the list is:", spaceleft)
输出
size of an empty list : 64
Now total size of a list : 96
capacity of the list is: 4
length of the list is: 4
space left in the list is: 0
示例 3:
# program to find capacity of the list
import sys
l = []
size = sys.getsizeof(l)
print("size of an empty list :", size)
# append five element in the list
l.append(1)
l.append(2)
l.append(3)
l.append(4)
l.append(5)
# calculate total size of the list after appending five element
print("Now total size of a list :", sys.getsizeof(l))
# calculate capacity of the list after appending five element
c = (sys.getsizeof(l)-size)//8
print("capacity of the list is:", c)
print("length of the list is:", len(l))
# calculate space left the list after appending five element
spaceleft =((sys.getsizeof(l)-size)-len(l)*8)//8
print("space left in the list is:", spaceleft)
输出
size of an empty list : 64
Now total size of a list : 128
capacity of the list is: 8
length of the list is: 5
space left in the list is: 3