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

是否有关于__cmp__如何在Python 2中为dict对象工作的描述?

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

是否有关于__cmp__如何在Python 2中为dict对象工作的描述?

如果您要问比较字典的工作原理,是这样的:

  • 要比较字典A和B,首先比较它们的长度。如果它们不相等,则返回cmp(len(A),len(B))。
  • 接下来,找到A中的密钥adiff,它是的最小密钥
    adiff not in B or A[adiff] != B[adiff]
    。(如果没有这样的键,则字典是相等的。)
  • 还要找到B中最小的键bdiff
    bdiff not in A or A[bdiff] != B[bdiff]
  • 如果adiff!= bdiff,则返回cmp(adiff,bdiff)。否则返回cmp(A [adiff],B [bdiff])。

用伪代码:

def smallest_diff_key(A, B):    """return the smallest key adiff in A such that adiff not in B or A[adiff] != B[bdiff]"""    diff_keys = [k for k in A if k not in B or A[k] != B[k]]    return min(diff_keys)def dict_cmp(A, B):    if len(A) != len(B):        return cmp(len(A), len(B))    try:        adiff = smallest_diff_key(A, B)    except ValueError:        # No difference.        return 0    bdiff = smallest_diff_key(B, A)    if adiff != bdiff:        return cmp(adiff, bdiff)    return cmp(A[adiff], b[bdiff])

这是从dictobject.c中的2.6.3实现翻译而来的。



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

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

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