关于比较不同类型对象的澄清

0 投票
2 回答
1165 浏览
提问于 2025-04-16 06:28

以下句子让我感到困惑(来自Guido在python.org上的教程):

“注意,不同类型的对象进行比较是合法的。结果是确定的,但又是任意的:这些类型是按名称排序的。因此,一个列表总是比一个字符串小,一个字符串总是比一个元组小,等等。”

这意味着对于:

a=[90]
b=(1)
a<b

结果应该是True。但实际上并不是这样!你能帮我解释一下吗?

另外,“结果是确定的但又是任意的”是什么意思呢?

2 个回答

3

请注意,你不应该再依赖这种行为了。有些内置类型是无法和其他内置类型进行比较的,而新的数据模型提供了一种方法,可以重载比较功能。

>>> set([1]) > [1]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: can only compare to a set

而且,这种功能在Python 3中完全被移除了:

>>> [1,2] > (3,4)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unorderable types: list() > tuple()
>>> [1,2] > "1,2"
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unorderable types: list() > str()
6

(1) 是一个整数。你可能想写的是 (1,),这是一个元组。

撰写回答