python – 字典__gt__和__lt__实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 字典__gt__和__lt__实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1650字,纯文字阅读大概需要3分钟。
内容图文
![python – 字典__gt__和__lt__实现](/upload/InfoBanner/zyjiaocheng/824/14ac58642ae64d6f9525fc0ce3541da2.jpg)
我一直在试验Python词典,并发现__gt__和__lt__是为字典实现的.
我已经对它们进行了测试,看起来它们在某种程度上比较了键,但我不清楚它是如何完成的;例如,我不太确定{1:1}> {‘0’:0}返回False(事实上,’0’> 100000也返回True).
是否有任何关于这两个功能实施细节的文件?
解决方法:
文档有section on comparisons.特别是:
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 "<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
内容总结
以上是互联网集市为您收集整理的python – 字典__gt__和__lt__实现全部内容,希望文章能够帮你解决python – 字典__gt__和__lt__实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。