如果变量为 0,return 1 和 return 0(如果变量为 1),什么是紧凑的方法?
What would be a compact way to return 1 if a variable is 0 and to return 0 if it is 1?
鉴于我提供了一个整数变量,如何使以下内容更紧凑(可能使用布尔值)?
indexTag = 0 # or 1
1 if indexTag == 0 else 0
你可以使用 not
:
not indexTag
它给你一个 布尔值 (True
或 False
),但是 Python 布尔值是 int
的子类并且确实有一个整数值(False
是 0
,True
是 1
)。您可以使用 int(not indexTag)
将其转换回整数,但如果这只是一个布尔值,何必呢?
或者你可以从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
或者您可以使用 ^
(XOR) 并简单地:
indexTag = 1 ^ indexTag
这实现了您想要的,因为..这就是 XOR 所做的:
+---------------+
| Input | Output|
+---+---+-------+
| A | B | |
+---+---+ |
| 0 | 0 | 0 |
| 0 | 1 | 1 | <
| 1 | 0 | 1 |
| 1 | 1 | 0 | <
+---+---+-------+
鉴于我提供了一个整数变量,如何使以下内容更紧凑(可能使用布尔值)?
indexTag = 0 # or 1
1 if indexTag == 0 else 0
你可以使用 not
:
not indexTag
它给你一个 布尔值 (True
或 False
),但是 Python 布尔值是 int
的子类并且确实有一个整数值(False
是 0
,True
是 1
)。您可以使用 int(not indexTag)
将其转换回整数,但如果这只是一个布尔值,何必呢?
或者你可以从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
或者您可以使用 ^
(XOR) 并简单地:
indexTag = 1 ^ indexTag
这实现了您想要的,因为..这就是 XOR 所做的:
+---------------+
| Input | Output|
+---+---+-------+
| A | B | |
+---+---+ |
| 0 | 0 | 0 |
| 0 | 1 | 1 | <
| 1 | 0 | 1 |
| 1 | 1 | 0 | <
+---+---+-------+