<分区>
我的代码不小心使用不等式将 dict 与 int 进行了比较,结果证明任何 dict 在测试时都评估为 True 大于 int。
d = {'a': 1, 'b': 2}
d > 0
Out[20]: True
d > 10e99999999999999
Out[21]: True
为什么会发生这种情况而不是类型错误?
这发生在 Python 2.7 上运行
<分区>
我的代码不小心使用不等式将 dict 与 int 进行了比较,结果证明任何 dict 在测试时都评估为 True 大于 int。
d = {'a': 1, 'b': 2}
d > 0
Out[20]: True
d > 10e99999999999999
Out[21]: True
为什么会发生这种情况而不是类型错误?
这发生在 Python 2.7 上运行
最佳答案
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/