pythonaltered_python – 字典__gt__和__lt__实现

我一直在试验Python词典,并发现__gt__和__lt__是为字典实现的.

我已经对它们进行了测试,看起来它们在某种程度上比较了键,但我不清楚它是如何完成的;例如,我不太确定{1:1}> {‘0’:0}返回False(事实上,’0’> 100000也返回True).

是否有任何关于这两个功能实施细节的文件?

解决方法:

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result).

行为的原因如下:

>>> '0' < 0

False

>>> 0 < '0'

True

在CPython中,选择的“一致但任意”的比较方法是按类型名称按字母顺序排序,’str’> “诠释”:

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

此行为是altered for Python 3.x,您无法再比较异构类型(或字典,就此而言):

>>> '0' > 0

Traceback (most recent call last):

File "", line 1, in

'0' > 0

TypeError: unorderable types: str() > int()

>>> {'a': None} > {'b': None}

Traceback (most recent call last):

File "", line 1, in

{'a': None} > {'b': None}

TypeError: unorderable types: dict() > dict()

就字典而言,它们的排序方式如下:

d1 > d2

变为:

(len(d1) > len(d2) or

(len(d1) == len(d2) and

sorted(d1.items()) > sorted(d2.items()))

(你可以在CPython source code中看到这个).因此,如果长度不同,则“较长”的长度为“较大”:

>>> {1: 2, 3: 4} > {1: 2}

True

如果它们具有匹配的键,则具有“较大”值的键是“较大”的:

>>> {1: 2} > {1: 1}

True

如果它们具有不匹配的键,则具有“较大”键的键“较大”:

>>> {1: 2} > {2: 1}

False

标签:python,dictionary,python-2-7,default

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值