__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
,无论尺寸x
和thing
。仅当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; }