可以相互比较的内置Python 3类型是什么? [英] What are built-in Python 3 types that can be compared to each other?

查看:88
本文介绍了可以相互比较的内置Python 3类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python 2, it was possible to compare objects of different types such as int to str by having an implicit comparison of the text string of types (that is, in lexicographic order, string 'int' is less than string 'str' and string 'list' is less than string 'tuple').

因此,在Python 2中, 5<'hello'返回 True .人们可以在为什么> 0在Python中为真"的答案中了解更多有关为什么允许这样做的信息.

Hence, in Python 2, 5 < 'hello' returns True. One can read more about why this was allowed in answer to Why is ''>0 True in Python?.

在Python 3中,这引发了 builtins.TypeError:不可排序的类型:int()<str()异常.

In Python 3, this raises builtins.TypeError: unorderable types: int() < str() exception.

网页

Python 3中严格的比较方法使其通常无法比较不同类型的对象.

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

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

Does it mean there are some built-in types or special cases where it would be possible for any built-in types to be compared without causing TypeError? I am not talking about custom types where the necessary dunder methods are implemented to properly support comparison.

推荐答案

所有这些都是有效的语句(它们的计算结果均为 True ):

All these are valid statements (and they all evaluate to True):

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

在这里看起来唯一奇怪的是 0.== False 1.== True .

The only thing that may look odd here is that 0. == False and 1. == True.

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

On the other hand, you can still reproduce what python 2 does by casting your value to an str before comparing it (this also evaluate to True):

str(5) < 'hello'

如果您确实需要此行为,则始终可以使用将进行强制转换/比较的函数.这样一来,您将保证不同类型的对象始终会以相同的方式进行比较,这似乎是python 2中的唯一约束.

If you really need this behaviour you can always have a function that will cast/compare. That way you'll guarantee that objects of different types will always compare the same way, which seems to be the only constraint in python 2.

def lt(a, b):
    return str(a) < str(b)

也许更好,您只能在需要时进行投射:

Or maybe even better, you can cast only when needed:

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

另一方面,如注释中所建议,在CPython的实现中,似乎可以通过以下方式进行比较:

On the other hand, as suggested in the comments, in CPython's implementation, it seems like comparison is done in the following way:

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类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆