python如何“否定”值:如果为真返回假,如果为假返回真
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17168046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python how to "negate" value : if true return false, if false return true
提问by user2239318
if myval == 0:
nyval=1
if myval == 1:
nyval=0
Is there a better way to do a toggle in python, like a nyvalue = not myval ?
有没有更好的方法在 python 中进行切换,比如 nyvalue = not myval ?
采纳答案by Martijn Pieters
Use the notboolean operator:
使用not布尔运算符:
nyval = not myval
notreturns a booleanvalue (Trueor False):
not返回一个布尔值(True或False):
>>> not 1
False
>>> not 0
True
If you must have an integer, cast it back:
如果您必须有一个整数,请将其转换回:
nyval = int(not myval)
However, the python booltype is a subclass of int, so this may not be needed:
但是,pythonbool类型是 的子类int,因此可能不需要:
>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True
回答by TerryA
In python, notis a boolean operator which gets the opposite of a value:
在python中,not是一个布尔运算符,它与值相反:
>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False
And True == 1and False == 0(if you need to convert it to an integer, you can use int())
而True == 1和False == 0(如果你需要将其转换为整数,则可以使用int())

