列表和 numpy 数组之间的比较
Comparison between a list and numpy array
好吧,我是 python 的新手,我最近开始学习 numpy 简介。先从numpy和list的比较看,numpy占用内存少space。但是在我在 IDLE shell 中尝试过之后,我很困惑。这是我所做的
list1=[1,2,3]
sys.getsizeof(list1)
48
a=np.array([1,2,3])
sys.getsizeof(a)
60
为什么我创建的 numpy 数组占用的空间比列表对象大?
首先,getsizeof
并不总是比较这两个对象大小的最佳方法。 From the docs:
Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
然而,为了回答您的问题,您在这里看到的只是 numpy
数组的额外开销,它将在如此小的输入样本上提供有偏差的结果。
如果您想知道只是numpy
数组中包含的数据的大小,您可以检查一个属性:
>>> a = np.array([1,2,3])
>>> a.nbytes
12
>>> a = np.array([1,2,3], dtype=np.int8)
>>> a.nbytes
3
This will not include the overhead:
Does not include memory consumed by non-element attributes of the array object.
好吧,我是 python 的新手,我最近开始学习 numpy 简介。先从numpy和list的比较看,numpy占用内存少space。但是在我在 IDLE shell 中尝试过之后,我很困惑。这是我所做的
list1=[1,2,3]
sys.getsizeof(list1)
48
a=np.array([1,2,3])
sys.getsizeof(a)
60
为什么我创建的 numpy 数组占用的空间比列表对象大?
首先,getsizeof
并不总是比较这两个对象大小的最佳方法。 From the docs:
Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
然而,为了回答您的问题,您在这里看到的只是 numpy
数组的额外开销,它将在如此小的输入样本上提供有偏差的结果。
如果您想知道只是numpy
数组中包含的数据的大小,您可以检查一个属性:
>>> a = np.array([1,2,3])
>>> a.nbytes
12
>>> a = np.array([1,2,3], dtype=np.int8)
>>> a.nbytes
3
This will not include the overhead:
Does not include memory consumed by non-element attributes of the array object.