【问题标题】:python how to "negate" value : if true return false, if false return truepython如何“否定”值:如果真返回假,如果假返回真
【发布时间】:2013-06-14 14:50:42
【问题描述】:
if myval == 0:
   nyval=1
if myval == 1:
   nyval=0

有没有更好的方法在 python 中进行切换,比如 nyvalue = not myval ?

【问题讨论】:

    标签: python boolean negate


    【解决方案1】:

    使用not boolean operator:

    nyval = not myval
    

    not 返回一个 boolean 值(True 或 False):

    >>> not 1
    False
    >>> not 0
    True
    

    如果你必须有一个整数,把它转换回来:

    nyval = int(not myval)
    

    不过,python bool 类型是int 的子类,所以可能不需要:

    >>> int(not 0)
    1
    >>> int(not 1)
    0
    >>> not 0 == 1
    True
    >>> not 1 == 0
    True
    

    【讨论】:

      【解决方案2】:

      在 python 中,not 是一个布尔运算符,它得到一个相反的值:

      >>> myval = 0
      >>> nyvalue = not myval
      >>> nyvalue
      True
      >>> myval = 1
      >>> nyvalue = not myval
      >>> nyvalue
      False
      

      还有True == 1和False == 0(如果需要转成整数,可以使用int())

      【讨论】:

        【解决方案3】:

        使用not,例如:

        return not myval
        

        【讨论】:

          【解决方案4】:
          variable = not (False | variable)
          

          类似于

          if variable == True:
              variable = False
          elif variable == False:
              variable = True
          

          【讨论】:

            猜你喜欢
            • 2021-10-15
            • 2016-05-03
            • 2017-04-01
            • 2019-03-10
            • 1970-01-01
            • 2011-01-13
            • 2013-11-09
            • 2016-05-10
            相关资源
            最近更新 更多