【发布时间】:2019-04-12 14:25:15
【问题描述】:
我看到有人问过类似的问题,但没有人回答我的问题。我对python比较陌生,不知道我在做什么。
【问题讨论】:
-
除非您不想显式使用不需要的布尔类型变量。 Python 在许多表达式中接受它为 True。
-
bool(1)返回True
我看到有人问过类似的问题,但没有人回答我的问题。我对python比较陌生,不知道我在做什么。
【问题讨论】:
bool(1) 返回True
用途:
>>> 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
>>>
【讨论】:
除非您不想显式使用 Boolean 类型变量,否则您不需要。 Python 在许多表达式中接受它为True:
print(True == 1)
print(False == 0)
输出:
True
True
在其他情况下,您当然可以使用 bool(1)。
print(bool(1))
print(bool(0))
输出:
True
False
【讨论】:
很简单:
bool(1)
这里有几个场景来展示:
print(bool(1))
将返回:真
print(bool(0))
将返回:假
【讨论】:
将1 转换为布尔类型:
print(bool(1))
返回True。
【讨论】: