__contains__如何用于ndarray?

发布于 2021-01-29 16:28:46

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

关注者
0
被浏览
142
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    我发现源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;
    }
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看