strange syntax for returning sign of number in python

时间:2017-04-10 02:15:43

标签: python syntax boolean tuples list-comprehension

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!

1 个答案:

答案 0 :(得分:3)

这是一种基于布尔值进行索引的方法。如下所示,TrueFalse分别在整数的上下文中评估为10

>>> 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的标志。