考虑到我提供了一个整数变量,下面怎么能变得更紧凑(也许使用布尔)?
indexTag = 0 # or 1
1 if indexTag == 0 else 0
Run Code Online (Sandbox Code Playgroud)
你可以使用not:
not indexTag
Run Code Online (Sandbox Code Playgroud)
它给你一个布尔(True或False),但Python布尔值是一个子类,int并且有一个整数值(False是0,True是1).你可以把它变成一个整数,int(not indexTag)但如果这只是一个布尔值,为什么要这么麻烦?
或者你可以从1中减去; 1 - 0是1,并且1 - 1是0:
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)