python – numpy内部存储数组的大小吗?


here的numpy数组的规范:

typedef struct PyArrayObject {
    PyObject_HEAD
    char *data;
    int nd;
    npy_intp *dimensions;
    npy_intp *strides;
    PyObject *base;
    PyArray_Descr *descr;
    int flags;
    PyObject *weakreflist;
} PyArrayObject;

当我查看numpy数组的规范时,我没有看到它存储数组的元素数量.那是真的吗?

不存储的优点是什么?

谢谢.

最佳答案 大小(即数组中元素的总数)计算为数组维度中值的乘积.该数组的长度为nd.

在实现numpy核心的C代码中,您将发现宏PyArray_SIZE(obj)的许多用法.这是宏的定义:

#define PyArray_SIZE(m) PyArray_MultiplyList(PyArray_DIMS(m), PyArray_NDIM(m))

不存储它的优点是不存储冗余数据.

点赞