我看到过类似的问题,但没有一个回答了我的问题。我对Python相对陌生,不知道该怎么做。
使用:
>>> 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
print(bool(1))
print(bool(0))
输出:
True
False
bool(1)
print(bool(1))
将返回:真
print(bool(0))
将返回:False
bool(1)
返回 True
,而 print(bool(1))
则会打印出 "True"。 - tedtanner将 1
转换为布尔类型:
print(bool(1))
这将返回True
。
bool(1)
returnsTrue
- Joel