Python2 比较元组和整数?

Python2 comparing tuple and int?

我目前正在将一些 Python2 代码移植到 Python3,我遇到了这个 gem:

v = (1, )
if v < 1:
    pass

现在,在 Python3 中它抛出一个错误:

TypeError: '<' not supported between instances of 'tuple' and 'int'.

这很好,因为您无法比较元组和整数。但是在 Python2 中这是允许的:

>>> (1, ) < 1
    False

我用谷歌搜索过,但找不到这种比较如何工作的示例。 How/why 上述示例的计算结果是否为 False

文档中描述了行为差异:

https://docs.python.org/2/library/stdtypes.html#comparisons

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.


正如您已经注意到的,比较元组和整数在 Python 3 中不再有效,原因是比较机制发生了一些变化:

https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons

  • The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < '', 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.
  • builtin.sorted() and list.sort() no longer accept the cmp argument providing a comparison function. Use the key argument instead. N.B. the key and reverse arguments are now “keyword-only”.
  • The cmp() function should be treated as gone, and the cmp() special method is no longer supported. Use lt() for sorting, eq() with hash(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)