python - 为什么 dicts 比任何 int 都大?

标签 python python-2.7 dictionary inequality

<分区>

我的代码不小心使用不等式将 dict 与 int 进行了比较,结果证明任何 dict 在测试时都评估为 True 大于 int。

d = {'a': 1, 'b': 2}
d > 0
Out[20]: True
d > 10e99999999999999
Out[21]: True

为什么会发生这种情况而不是类型错误?

这发生在 Python 2.7 上运行

最佳答案

来自Python 2.7 documentation :

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).

Python 3.3 documentation取而代之的是:

The <, <=, > and >= operators will raise a TypeError exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.

这意味着从 Python 3 开始,您所看到的不再可能,而是这种比较会像您预期的那样产生 TypeError

关于python - 为什么 dicts 比任何 int 都大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43944827/

相关文章:

python - 我如何随机选择一个数学运算符并用它提出重复出现的数学问题?

Python Pandas 全局 vs 传递变量

python 下划线 : learn python the hard way exercise 40

python - 如何让Python程序读取文件中的行

python - 如何在 Python 中使用并行处理过滤器?

python - 使用 Python 刷新本地网页

google-app-engine - 使用 ndb 获取、修改和放置一批实体的最有效方法

python-2.7 - 重命名 matplotlib 中的 x 轴值

如果满足条件,python更改嵌套字典中的值

python - 更新字典的字典内的值