__contains__ 如何为 ndarrays 工作? [英] How does __contains__ work for ndarrays?
问题描述
我不知道 __contains__
如何用于 ndarrays.我在找的时候找不到相关的文档.它是如何工作的?它是否在任何地方都有记录?
我在 numpy/core/src/multiarray/sequence.c
.正如源代码中的评论,
x 中的东西
相当于
(x == thing).any()
对于 ndarray x
,不管 x
和 thing
的维度.这仅在 thing
是标量时才有意义;当 thing
不是标量时广播的结果会导致我观察到的奇怪结果,以及像 array([1, 2, 3]) in array(1)
array([1, 2, 3]) 这样的奇怪现象代码>,我没想到要尝试.确切来源是
static intarray_contains(PyArrayObject *self, PyObject *el){/* 等价于 (self == el).any() */int ret;PyObject *res, *any;res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self,el, Py_EQ));如果(res == NULL){返回-1;}any = PyArray_Any((PyArrayObject *)res, NPY_MAXDIMS, NULL);Py_DECREF(res);ret = PyObject_IsTrue(any);Py_DECREF(any);返回 ret;}
>>> x = numpy.array([[1, 2],
... [3, 4],
... [5, 6]])
>>> [1, 7] in x
True
>>> [1, 2] in x
True
>>> [1, 6] in x
True
>>> [2, 6] in x
True
>>> [3, 6] in x
True
>>> [2, 3] in x
False
>>> [2, 1] in x
False
>>> [1, 2, 3] in x
False
>>> [1, 3, 5] in x
False
I have no idea how __contains__
works for ndarrays. I couldn't find the relevant documentation when I looked for it. How does it work? And is it documented anywhere?
I found the source for ndarray.__contains__
, in numpy/core/src/multiarray/sequence.c
. As a comment in the source states,
thing in x
is equivalent to
(x == thing).any()
for an ndarray x
, regardless of the dimensions of x
and thing
. This only makes sense when thing
is a scalar; the results of broadcasting when thing
isn't a scalar cause the weird results I observed, as well as oddities like array([1, 2, 3]) in array(1)
that I didn't think to try. The exact source is
static int
array_contains(PyArrayObject *self, PyObject *el)
{
/* equivalent to (self == el).any() */
int ret;
PyObject *res, *any;
res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self,
el, Py_EQ));
if (res == NULL) {
return -1;
}
any = PyArray_Any((PyArrayObject *)res, NPY_MAXDIMS, NULL);
Py_DECREF(res);
ret = PyObject_IsTrue(any);
Py_DECREF(any);
return ret;
}
这篇关于__contains__ 如何为 ndarrays 工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!