• [python基础] python 2与python 3之间的区别 —— 不同数据类型间的运算


    python 3的更新中,不再支持 str 和 int 直接判定

    >>> a = '10'
    >>> a > 9
    Traceback (most recent call last):
      File "<pyshell#18>", line 1, in <module>
        a > 9
    TypeError: '>' not supported between instances of 'str' and 'int'

    python 2中

    >>> a = '1'
    >>> a > 10
    True
    >>> a > 100000
    True

    手册中的描述

    ...the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently

    • 任何两个对象都可以比较
    • 相同类型的对象(实例),如果是数字型(int/float/long/complex),则按照简单的大小来比较;如果是非数字型,且类(型)中定义了__cmp__(含__gt__,__lt__等)则按照__cmp__来比较,否则按照地址(id)来比较
    • 不同类型的对象(实例),如果其中一个比较对象是数字型(int/float/long/complex等),则数字型的对象<其它非数字型的对象;如果两个都是非数字型的对象,则按照类型名的顺序比较,如{} < "abc"(按照"dict" < "str"),而"abc" > [1,2], "abc" < (1,2)。
    • 对于自定义的类(型)实例,如果继承自基本类型,则按照基本类型的规则比较(1-3)。否则,old-style class < new-style class, new-style class之间按照类型名顺序比较,old-style class之间按照地址进行比较
    • bool类型是int的子类,且True=1, False=0,比较时按照1-4来比较,如True > -1, True < 4.2, True < "abc"等

    也就是python 2中的数字型对象 < 其他非数字型的对象,字符串>数字 的表达式会始终返回True

    这么看起来确实3比较严谨一些啊,避免一些可能出现的问题

  • 相关阅读:
    [luogu3334]抛硬币
    [luogu3706]硬币游戏
    [luogu4548]歌唱王国
    [hdu4652]Dice
    [atAGC013F]Two Faced Cards
    [atAGC045F]Division into Multiples
    [atAGC045E]Fragile Balls
    [atAGC045D]Lamps and Buttons
    [luogu5574]任务分配问题
    [luogu4331]数字序列
  • 原文地址:https://www.cnblogs.com/Liubit/p/7635062.html
Copyright © 2020-2023  润新知