__contains__如何用于ndarray?


问题内容
>>> 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。我找不到相关的文档。它是如何工作的?并且在任何地方都有记录吗?


问题答案:

我发现源ndarray.__contains__numpy/core/src/multiarray/sequence.c。作为消息来源的评论,

thing in x

相当于

(x == thing).any()

用于ndarray
x,无论尺寸xthing。仅当thing是标量时才有意义;广播的结果thing不是标量时,会导致我观察到怪异的结果,以及array([1, 2, 3]) in array(1)我没想尝试的奇怪之处。确切的来源是

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;
}