【问题标题】:How to convert number 1 to a Boolean in python如何在python中将数字1转换为布尔值
【发布时间】:2019-04-12 14:25:15
【问题描述】:

我看到有人问过类似的问题,但没有人回答我的问题。我对python比较陌生,不知道我在做什么。

【问题讨论】:

标签: python boolean


【解决方案1】:

用途:

>>> bool(1)
True
>>> bool(0)
False
>>> int(bool(1))
1
>>> int(bool(0))
0

也可以转换回来。

或者一个可能更快的聪明技巧是:

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

转换回来:

>>> int(not not 1)
1
>>> int(not not 0)
0
>>> 

【讨论】:

    【解决方案2】:

    当作为参数传递给bool()时,只有以下值会返回False

    • 错误
    • 任何数字类型的零。例如,0、0.0、0j
    • 空序列。例如,()、[]、''。
    • 空映射。例如,{}
    • 具有返回 0 或 False 的 bool() 或 len() 方法的类的对象

    其他一切都返回 True

    Source1 Source2

    【讨论】:

      【解决方案3】:

      除非您不想显式使用 Boolean 类型变量,否则您不需要。 Python 在许多表达式中接受它为True

      print(True == 1)
      print(False == 0)
      

      输出:

      True
      True
      

      在其他情况下,您当然可以使用 bool(1)。

      print(bool(1))
      print(bool(0))
      

      输出:

      True
      False
      

      【讨论】:

        【解决方案4】:

        很简单:

        bool(1)
        

        这里有几个场景来展示:

        print(bool(1))
        

        将返回:真

        print(bool(0))
        

        将返回:假

        【讨论】:

          【解决方案5】:

          1 转换为布尔类型:

          print(bool(1))
          

          返回True

          【讨论】:

            猜你喜欢
            • 2017-09-27
            • 2022-11-10
            • 1970-01-01
            • 1970-01-01
            • 2018-12-20
            • 1970-01-01
            • 2022-07-28
            • 2014-11-21
            • 1970-01-01
            相关资源
            最近更新 更多