为什么以下代码是正确的?
>>> foo = {}
>>> foo > 1
True
>>> foo < 1
False
>>> foo == 0
False
>>> foo == -1
False
>>> foo == 1
False
我知道我想要的是 len(foo) > 1,但作为一个初学者,这让我感到惊讶。
为什么以下代码是正确的?
>>> foo = {}
>>> foo > 1
True
>>> foo < 1
False
>>> foo == 0
False
>>> foo == -1
False
>>> foo == 1
False
我知道我想要的是 len(foo) > 1,但作为一个初学者,这让我感到惊讶。
在Python 2.x中,不同类型之间的比较是基于类型名称进行的,但在Python 3.x中已被禁止。无论如何,在Python 2.x中,排序保证对于特定的Python实现和版本会给出相同的结果,但排序本身没有定义。
“int” > “dict”
,所以为什么foo < 1
呢?” - Tim PietzckerPython 2:
>>> foo == 0
False
>>> foo < 0
False
>>> not (foo <= 0)
True
so:
>>> foo > 0
True
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
>>>
1
,而是大于所有整数。 - David Robinsonfoo > float('inf')
的结果为True
。对于列表、元组等序列以及字典也适用此规则。虽然这并没有解释其原理,但希望这能使事情变得更加明了。 - Joe Kington