比较运算符对字典有什么作用? [英] What do comparison operators do on dictionaries?

查看:88
本文介绍了比较运算符对字典有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题

>>> d1 = {"john":40, "peter":45}
>>> d2 = {"john":466, "peter":45}
>>> d1 > d2
False

比较运算符在比较两个字典时会做什么以及如何输出错误

What does the comparison operator do while comparing two dicts and how does it output False?

推荐答案

由于这些字典的长度相等,因此我们发现对应值不相等的最小键,即'john'。然后将字典的键值进行比较。

Since these dicts have equal length, we find the smallest key for which the corresponding values are unequal, i.e. 'john'. Then the dicts are compared on the value of that key.

演示:

>>> d1 = {"john":40, "peter":45}
>>> d2 = {"john":466, "peter":45}
>>> d1 < d2
True
>>> d2['john'] = 39
>>> d1 < d2
False

由于 Guido的提交来自20年前:

$ git show a0a69b8
commit a0a69b8b429f3d4c91f1c432247cfda017505976
Author: Guido van Rossum <guido@python.org>
Date:   Thu Dec 5 21:55:55 1996 +0000

    Experimental new implementation of dictionary comparison.  This
    defines that a shorter dictionary is always smaller than a longer one.
    For dictionaries of the same size, the smallest differing element
    determines the outcome (which yields the same results as before,
    without explicit sorting).

未记录,并且dict比较代码已在Python 3中删除,所以我不会依靠它来做任何重要的事情。相关的CPython来源是此处

It is not documented, and the dict comparison code is removed in Python 3, so I wouldn't rely on that for anything important. The relevant CPython source is here.

有趣的事实:显然,在旧版本的Python中,某些dict比较可能会使运行时崩溃,甚至导致Windows 98重新启动。嘿。

Fun fact: Apparently, in older versions of Python, some dict comparisons could crash the runtime and could even cause Windows 98 to reboot. Heh.

这篇关于比较运算符对字典有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆