我一直在试验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