How does Python 2.7 compare items inside a list

How does Python 2.7 compare items inside a list,第1张

How does Python 2.7 compare items inside a list

CPython’s underlying implementation will skip the equality check (

==
) for
items in a list if items are identical (
is
).

CPython uses this as an optimization assuming identity implies equality.

This is documented in
PyObject_RichCompareBool,
which is used to compare items:

Note: If o1 and o2 are the same object, PyObject_RichCompareBool() will
always return 1 for Py_EQ and 0 for Py_NE.

From the
listobject.c
implementation:

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

As you can see as long as

RichCompareBool
is
1
(
True
) the items are not
checked.

And from
object.c‘s
implementation of

PyObject_RichCompareBool
:

if (v == w) {    if (op == Py_EQ)        return 1;    else if (op == Py_NE)        return 0;}// ... actually deep-compare objects

To override this you’ll have to compare the items manually.



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4984773.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存