鉴于我提供了一个整数变量,如何使以下内容更紧凑(可能使用 boolean 值)?
indexTag = 0 # or 1
1 if indexTag == 0 else 0
最佳答案
你可以使用不
:
not indexTag
它给你一个 boolean 值(True
或False
),但是 Python boolean 值是 int
的子类并且确实有一个整数值(False
是 0
,True
是 1
)。您可以使用 int(not indexTag)
将其转换回整数,但如果这只是一个 boolean 值,何必呢?
或者你可以从 1 中减去; 1 - 0
是 1
,1 - 1
是 0
:
1 - indexTag
或者您可以使用条件表达式:
0 if indexTag else 1
演示:
>>> 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
关于python - 如果变量为 0 则返回 1,如果变量为 1 则返回 0 的紧凑方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32866760/