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

标签 python boolean

鉴于我提供了一个整数变量,如何使以下内容更紧凑(可能使用 boolean 值)?

indexTag = 0 # or 1
1 if indexTag == 0 else 0

最佳答案

你可以使用:

not indexTag

它给你一个 boolean 值(TrueFalse),但是 Python boolean 值是 int 的子类并且确实有一个整数值(False0True1)。您可以使用 int(not indexTag) 将其转换回整数,但如果这只是一个 boolean 值,何必呢?

或者你可以从 1 中减去; 1 - 011 - 10:

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/

相关文章:

PHP 处理 IF 语句中的多个子句

python - '/' or '\' 路径?

python - 使用 Pandas、Python 将数据附加到 HDF5 文件

algorithm - 在我的递归方法中继续越界以导航并查找 4X4 矩阵中的所有字母组合

button - javafx - 根据 boolean 值绑定(bind)按钮

Python - 确定井字游戏的赢家

python - 如何消除相等运算符的 python3 弃用警告?

python - Numpy 方法检查张量中的任何两个样本是否相同

python - Pyinstaller 3 使用 --onefile 添加数据文件

javascript - react setState : using checkbox to change boolean value