從1<2<3的語法糖提及

python有一個頗有意思的語法糖你能夠直接寫1<2<3。html

這複合咱們一般意義上的數學不等式,但對學過C等語言實際上是有疑惑的。python

咱們知道不等式返回的實際上是個Bool值,在C中是1,0所以C中下面狀況是正確的express

0<0<1code

所以咱們看下面這個狀況htm

True == True == False
#False
False == False == True
#False

從一般意義來講==號從右往左結合,不管如何值都應該是True,可是結果確是False文檔

這就是源於python的一個語法糖,對於運算優先級的規定。get

全部比較類型的運算符擁有一樣的優先級,會從左至右連接起來共同做爲一個比較段( all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section)。數學

in, not in, is, is not, <, <=, >, >=, !=, ==

好比一個典型的True == True == False它實質是以下的邏輯關係it

(True == True) and (True == False)io

文檔中說明a op1 b op2 c ... y opN z實質至關於a op1 b and b op2 c and ... y opN z

因此雖然-2<-1<0符合咱們正常數學上的邏輯,但這只是一個特例,正如評論中指出的1<5>3依然返回True
正是由於它符合1<5 and 5>3

參考
python operation priority

相關文章
相關標籤/搜索