python - 列表和 numpy 数组之间的比较

标签 python python-3.x numpy numpy-ndarray

我是 python 新手,最近开始使用 numpy intro。先从numpy和list的比较开始,numpy占用的内存存储空间更少。但在我在 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 数组之间的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52261119/

相关文章:

python - spine - 从复杂类型继承且派生类实现 xml 属性时出错

python - 如何使用列表值创建颜色渐变一维热图(带状图)?

python-3.x - 在 PyGame 2 中播放视频

python - 用python卷积周期图像

c# - 在 Unity3D 游戏脚本中使用带有 PIP 包的 Python 脚本

python - 尝试安装新的 Python 包时出现错误

python - HTML 表格特定行抓取

python - 无法加载 virtualenv 的 Python 3.5 解释器

python - 确定数组中的重复值

相当于 R 函数 sweep() 的 Python numpy 或 pandas