内置的Python 3种可以相互比较的类型是什么?

What are built-in Python 3 types that can be compared to each other?

在 Python 2 中,可以通过隐式比较类型的文本字符串(即,按字典顺序,字符串 'int' 小于字符串 'str' 并且字符串 'list' 小于字符串 'tuple').

因此,在Python2中,5 < 'hello'returnsTrue。人们可以在 Why is ''>0 True in Python?.

的回答中阅读更多关于为什么允许这样做的信息

在 Python 3 中,这会引发 builtins.TypeError: unorderable types: int() < str() 异常。

web page 表示

The strict approach to comparing in Python 3 makes it generally impossible to compare different types of objects.

这是否意味着存在某些内置类型或特殊情况,可以比较任何内置类型而不会导致 TypeError?我不是在谈论自定义类型,其中实现了必要的 dunder 方法以正确支持比较。

所有这些都是有效的陈述(它们的计算结果都是 True):

0 < True
0 < 1.
0. < True
{0} < frozenset((0, 1))

这里唯一可能看起来奇怪的是 0. == False1. == True.

另一方面,您仍然可以通过在比较之前将您的值转换为 str 来重现 python 2 的作用(这也计算为 True):

str(5) < 'hello'

如果你真的需要这种行为,你总是可以有一个函数 cast/compare。这样你就可以保证不同类型的对象总是以相同的方式进行比较,这似乎是 python 2.

中的唯一约束。
def lt(a, b):
    return str(a) < str(b)

或者更好的是,您可以仅在需要时投射:

def lt(a, b):
  try: 
    return a < b
  except TypeError: 
    return str(a) < str(b)

另一方面,正如评论中所建议的,在 CPython 的实现中,比较似乎是通过以下方式完成的:

def lt(a, b):
  try: 
    return a < b
  except TypeError: 
    if a is None:
      return True
    if b is None: 
      return False
    if isinstance(a, numbers.Number):
      return True
    if isinstance(b, numbers.Number):
      return False
    return str(type(a)) < str(type(b))

我之前已经在网上查过了,看来它们在 Python 3 中确实是无法排序的,除了上面提到的少数特殊情况。

The change usually manifests itself in sorting lists: in Python 3, lists with items of different types are generally not sortable. If you need to sort heterogeneous lists, or compare different types of objects, implement a key function to fully describe how disparate types should be ordered.
Source

我不知道为什么,但有些人找到了使用 Python 3.

重现 Python 2 行为的方法

也许你应该看看 or that. This question 还强调了 2011 年的变化:

Found it: Buried in PEP 3100: "Comparisons other than == and != between disparate types will raise an exception unless explicitly supported by the type"