【发布时间】:2013-09-04 19:00:44
【问题描述】:
所以这一直困扰着我,我无法在网上找到任何关于它的信息。有人可以在python中解释这种行为吗?为什么它返回 True 而不是抛出异常?谢谢
In [1]: 1 < [1, 2, 3]
Out[1]: True
【问题讨论】:
-
这里有一些关于这种行为的信息(最后一段):docs.python.org/2.7/tutorial/…
标签: python
所以这一直困扰着我,我无法在网上找到任何关于它的信息。有人可以在python中解释这种行为吗?为什么它返回 True 而不是抛出异常?谢谢
In [1]: 1 < [1, 2, 3]
Out[1]: True
【问题讨论】:
标签: python
它确实抛出异常——无论如何,这些天来:
$ python3
Python 3.3.0 (default, Apr 17 2013, 13:40:43)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 < [1,2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < list()
过去,Python 过去常常让比较像这样通过,因为有时能够在异构容器中自动对所有内容进行排序很方便,但这导致的错误多于其便利性,因此它在 Python 3 中得到了修复.
【讨论】:
这是一种使排序更容易的尝试。 Python 试图使没有有意义的比较操作的对象以一致但任意的顺序进行比较。在 Python 3 中,他们改变了它;这将是 Python 3 中的 TypeError。
【讨论】:
如果我没记错的话,您在 py2 中看到的行为实际上是在比较类型。
>>> 1 < [1,2,3]
True
>>> 1 > [1,2,3]
False
>>> int < list
True
>>> int > list
False
随着我的深入研究,我认为它比较了类型的名称,尽管可能有些间接,也可能通过其中之一进行比较,尽管我不能说:
>>> repr(int)
"<type 'int'>"
>>> int.__name__
'int'
>>> repr(list)
"<type 'list'>"
>>> list.__name__
'list'
>>> 'int' < 'list'
True
>>> "<type 'int'>" < "<type 'list'>"
True
【讨论】: