Why is int(50)<str(5) in python 2.x?

前端 未结 4 491
南笙
南笙 2021-01-13 00:32

In python 3, int(50)<\'2\' causes a TypeError, and well it should. In python 2.x, however, int(50)<\'2\' returns True

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 00:52

    The reason why these comparisons are allowed, is sorting. Python 2.x can sort lists containing mixed types, including strings and integers -- integers always appear first. Python 3.x does not allow this, for the exact reasons you pointed out.

    Python 2.x:

    >>> sorted([1, '1'])
    [1, '1']
    >>> sorted([1, '1', 2, '2'])
    [1, 2, '1', '2']
    

    Python 3.x:

    >>> sorted([1, '1'])
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unorderable types: str() < int()
    

提交回复
热议问题