python - __contains__ 如何为 ndarrays 工作?

标签 python numpy

>>> 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。找的时候没找到相关文档。它是如何工作的?是否在任何地方记录了它?

最佳答案

我在 numpy/core/src/multiarray/sequence.c 中找到了 ndarray.__contains__ 的源代码.作为源状态中的评论,

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

关于python - __contains__ 如何为 ndarrays 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320624/

相关文章:

python - 从 NumPy 版本在 Tensorflow 中构建 Softmax 的导数

python - 如何使用 numpy 在线性时间内通过唯一值获取累积计数?

python - 有效地将 2D numpy mask 在所有方向上扩展 n 个单元格

python - 如何在Python中显式移动光标

python - 如何操作以下 numpy.where 数组

python - 如何在 Python 中搜索和替换 utf-8 特殊字符?

python - Django 中的垃圾收集对象

python - 绘制目录中的所有数据文件

python - 来自搜索 api 的推文是否重叠?

python - 给定数据框中的 pd.Interval 列,过滤落在 Interval 范围内的值