__contains__如何用于ndarray? [英] How does __contains__ work for ndarrays?
问题描述
>>> 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
我不知道__contains__
如何用于ndarrays.我找不到相关的文档.它是如何工作的?并且在任何地方都有记录吗?
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
等同于
(x == thing).any()
ndarray x
的
,与x
和thing
的尺寸无关.仅当thing
是标量时才有意义; thing
不是标量时的广播结果会导致我观察到怪异的结果,以及我不曾尝试尝试的array([1, 2, 3]) in array(1)
之类的怪异现象.确切的来源是
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__如何用于ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!