如果变量为0则返回1的紧凑方法是什么?如果变量为1则返回0?

d3p*_*3pd 3 python boolean

考虑到我提供了一个整数变量,下面怎么能变得更紧凑(也许使用布尔)?

indexTag = 0 # or 1
1 if indexTag == 0 else 0
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

你可以使用not:

not indexTag
Run Code Online (Sandbox Code Playgroud)

它给你一个布尔(TrueFalse),但Python布尔值是一个子类,int并且有一个整数值(False0,True1).你可以把它变成一个整数,int(not indexTag)但如果这只是一个布尔值,为什么要这么麻烦?

或者你可以从1中减去; 1 - 01,并且1 - 10:

1 - indexTag
Run Code Online (Sandbox Code Playgroud)

或者您可以使用条件表达式:

0 if indexTag else 1
Run Code Online (Sandbox Code Playgroud)

演示:

>>> for indexTag in (0, 1):
...     print 'indexTag:', indexTag
...     print 'boolean not:', not indexTag
...     print 'subtraction:', 1 - indexTag
...     print 'conditional expression:', 0 if indexTag else 1
...     print
... 
indexTag: 0
boolean not: True
subtraction: 1
conditional expression: 1

indexTag: 1
boolean not: False
subtraction: 0
conditional expression: 0
Run Code Online (Sandbox Code Playgroud)