【问题标题】:Dictionary __gt__ and __lt__ implementation字典 __gt__ 和 __lt__ 的实现
【发布时间】:2015-04-28 10:15:54
【问题描述】:

我一直在试验 Python 字典,发现 __gt____lt__ 是为字典实现的。

我已经对它们进行了测试,似乎它们以某种方式比较了密钥,但我不太清楚这是如何完成的;例如,我不太确定{1: 1} > {'0': 0} 如何返回False(事实上,'0' > 100000 也返回True)。

有没有文件详细说明这两个功能的实现?

【问题讨论】:

  • 仅在 Python 2.x 中 - 在 3.x 中你会得到TypeError: unorderable types: dict() > dict()。您的问题是关于字典比较,还是为什么字符串“大于”数字?
  • 在 python repr (Python 2.7.9 Anaconda 2.2.0) 我可以输入以下代码:
    tmp1 = dict();tmp2 = dict();tmp1[1] = 1;tmp2['1'] = 2;tmp2 > tmp1 并返回 True... 我不太懂确定这是怎么做的……

标签: python python-2.7 dictionary default


【解决方案1】:

文档有一个section on comparisons。特别是:

不同类型的对象,除了不同的数值类型和不同的字符串类型,从不比较相等;此类对象的排序一致但任意(因此对异构数组进行排序会产生一致的结果)。

如下行为的原因:

>>> '0' < 0
False
>>> 0 < '0'
True

在 CPython 中,“一致但任意”的比较方法选择是按类型名称的字母顺序排列,'str' &gt; 'int':

CPython 实现细节:除数字外的不同类型的对象按其类型名称排序;不支持正确比较的相同类型的对象按其地址排序。

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

>>> '0' > 0
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    '0' > 0
TypeError: unorderable types: str() > int()
>>> {'a': None} > {'b': None}
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    {'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

【讨论】:

  • 和字典关键字在比较之前先排序?例如,如果我创建一个包含混合类型关键字(str、int 等)的字典,将什么关键字与什么进行比较?
  • 不完全等同于sorted(d1.items()) &gt; sorted(d2.items());首先比较长度。
  • 在item比较之前,必须做一个key比较,如:sorted(d1.keys()) &gt; sorted(d2.keys())。例如{'1': 1} &gt; {1: 1}; 返回True,而{1: 1} &gt; {'1': 1} 返回False。我猜这个实现包含类似if sorted(self.keys()) == sorted(other.keys()) then: return sorted(self.keys()) &gt; sorted(other.keys())
  • @LorenzoTrojan:你把items()values()搞混了吗?
  • @LorenzoTrojan 不,它没有“进行密钥比较”items 包括键和值。如果您想查看 CPython 的实际实现,请转到源代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 2020-11-08
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
相关资源
最近更新 更多