python没有数组概念,numpy:“ array_like”对象的正式定义?

事实证明,几乎所有东西在技术上都类似于数组。 “类似数组”更多地是关于如何解释输入的陈述,而不是对输入内容的限制。 如果参数记录为类似数组的形式,则NumPy将尝试将其解释为数组。

除了几乎是重言式的之外,没有像数组这样的形式上的正式定义-像数组一样的是__array_struct__可以转换为ndarray的任何Python对象。要超出此范围,您需要研究源代码。

NPY_NO_EXPORT PyObject *

PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,

int max_depth, int flags, PyObject *context)

{

/*

* This is the main code to make a NumPy array from a Python

* Object. It is called from many different places.

*/

PyArrayObject *arr = NULL, *ret;

PyArray_Descr *dtype = NULL;

int ndim = 0;

npy_intp dims[NPY_MAXDIMS];

/* Get either the array or its parameters if it isn't an array */

if (PyArray_GetArrayParamsFromObject(op, newtype,

0, &dtype,

&ndim, dims, &arr, context) < 0) {

Py_XDECREF(newtype);

return NULL;

}

...

__array_struct__特别有趣,其注释列举了__array_struct__期望的对象类型:

NPY_NO_EXPORT int

PyArray_GetArrayParamsFromObject(PyObject *op,

PyArray_Descr *requested_dtype,

npy_bool writeable,

PyArray_Descr **out_dtype,

int *out_ndim, npy_intp *out_dims,

PyArrayObject **out_arr, PyObject *context)

{

PyObject *tmp;

/* If op is an array */

/* If op is a NumPy scalar */

/* If op is a Python scalar */

/* If op supports the PEP 3118 buffer interface */

/* If op supports the __array_struct__ or __array_interface__ interface */

/*

* If op supplies the __array__ function.

* The documentation says this should produce a copy, so

* we skip this method if writeable is true, because the intent

* of writeable is to modify the operand.

* XXX: If the implementation is wrong, and/or if actual

* usage requires this behave differently,

* this should be changed!

*/

/* Try to treat op as a list of lists */

/* Anything can be viewed as an object, unless it needs to be writeable */

}

因此,通过研究源代码,我们可以得出类似数组的结论

一个NumPy数组,或者

NumPy标量,或

Python标量,或者

任何支持PEP 3118缓冲区接口的对象,或者

支持__array_struct__或object接口的任何对象,或

提供object功能的任何对象,或

任何可以视为列表列表的对象,或者

什么! 如果它不属于其他情况之一,它将被视为0维数组object dtype。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值