栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

How does Python 2.7 compare items inside a list

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/393666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号