简体   繁体   English

为什么空字典大于1?

[英]Why is an empty dictionary greater than 1?

Why is the following code true? 为什么以下代码为真?

>>> foo = {}
>>> foo > 1
True
>>> foo < 1
False
>>> foo == 0
False
>>> foo == -1
False
>>> foo == 1
False

I understand what I wanted was len(foo) > 1, but as a beginner this surprised me. 我明白我想要的是len(foo)> 1,但作为初学者,这让我感到惊讶。

From the docs : 来自文档

The operators <, >, ==, >=, <=, and != compare the values of two objects. 运算符<,>,==,> =,<=和!=比较两个对象的值。 The objects need not have the same type. 对象不必具有相同的类型。 If both are numbers, they are converted to a common type. 如果两者都是数字,则将它们转换为通用类型。 Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. 否则,不同类型的对象总是比较不相等,并且一致但是任意地排序。 You can control comparison behavior of objects of non-builtin types by defining a __cmp__ method or rich comparison methods like __gt__ , described in section 3.4. 您可以通过定义__cmp__方法或丰富的比较方法(如__gt__来控制非内置类型对象的比较行为,如3.4节所述。

(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.) (这种不寻常的比较定义用于简化操作的定义,如排序和运算符中的in和not。将来,不同类型的对象的比较规则可能会发生变化。)

rich comparison between incompatible types is based on the name(?) of the type in python2.x and has been disallowed in python3.x. 不兼容类型之间的丰富比较基于python2.x中类型的名称(?),并且在python3.x中已被禁止。

In any event, in python2.x, the ordering is guaranteed to give the same results for a particular python implementation and version, but the ordering itself is not defined. 无论如何,在python2.x中,保证为特定的python实现和版本提供相同的结果,但是没有定义排序本身。

I think this may have arisen from the fact that comparison operators only need to be partially defined to be derived, ie if you can test for == and < then you can derive the rest of the operators, <= is (< or ==), > is not <=, etc. so in the case of foo = {} you can get: 我认为这可能是因为比较运算符只需要部分定义为派生,即如果你可以测试==和<那么你可以派生出其余的运算符,<= is(<或== ),>不是<=等等,所以在foo = {}的情况下你可以得到:

Python 2: Python 2:

>>> foo == 0
False
>>> foo < 0
False
>>> not (foo <= 0)
True
so:
>>> foo > 0
True

python 3: python 3:

>>> foo = {}
>>> foo < 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < int()
>>> foo > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() > int()
>>> foo == 0
False
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM