您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python 2.7如何比较列表中的项目

Python 2.7如何比较列表中的项目

==如果项目相同(is),cpython的基础实现将跳过列表中项目的相等性检查()。

cpython使用此作为优化,假设身份暗示平等。

这记录在PyObject_RichCompareBool中,用于比较项目:

注意:如果o1和o2是同一对象,则PyObject_RichCompareBool()对于Py_EQ将始终返回1,对于Py_NE将始终返回0。

listobject.c实现中:

/* Search for the first index where items are different */
for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
    int k = PyObject_RichCompareBool(vl->ob_item[i],
                                     wl->ob_item[i], Py_EQ);
    // k is 1 if objects are the same
    // because of RichCmopareBool's behavIoUr
    if (k < 0)
        return NULL;
    if (!k)
        break;
}

正如你可以看到,只要RichCompareBool1True)的项目不检查。

object.c的实现PyObject_RichCompareBool

/* Quick result when objects are the same.
   Guarantees that identity implies equality. */
if (v == w) {
    if (op == Py_EQ)
        return 1;
    else if (op == Py_NE)
        return 0;
}
// ... actually deep-compare objects

要覆盖此内容,您必须手动比较各项。

python 2022/1/1 18:44:32 有297人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶