So the below snippet of code returns the sign of x:
x = -15 (1, -1)[x < 0]
I have a hard time understanding WHY this syntax works. In particular, how come you can write a tuple following a list of booleans and get one or the other value in the tuple from that....Someone please explain this syntax!
答案 0 :(得分:3)
这是一种基于布尔值进行索引的方法。如下所示,True
和False
分别在整数的上下文中评估为1
和0
:
>>> int(True)
1
>>> int(False)
0
此外,(1, -1)
是一个元组,一个可以编入索引的序列对象:
>>> (314159,271828)[0]
314159
>>> (314159,271828)[1]
271828
结合这两个事实,你应该能够辨别:
(1, -1)[x < 0]
当1
为假时,会给您x < 0
,当{1}}为真时,{p}会给您-1
。这基本上是x
的标志。