python中可以通過串聯(lián)比較操作符率碾,舉例說明:
1. a < b < c? 等同于 a < b and b < c,對于if條件可寫成下式:
? ? if a < b < c:
? ? ? ? pass
2. 所有的比較操作符(">" | "<" | "==" | ">=" | "<=" | "!=" | "is" ["not"] | ["not"] "in")具有相同的優(yōu)先級(jí)
3. 比較操作符的優(yōu)先級(jí)低于算數(shù)運(yùn)算符有巧、平移運(yùn)算符和位運(yùn)算符
4. 串聯(lián)比較操作符規(guī)則:
4.1 比較操作最終返回值為True或False
4.2 比較操作符可以任意串聯(lián),例如
x < y <= z 等同于 x < y and y <= z铅忿,注意:y變量值不可變且可獲取多次如有必要
4.3 若a, b, c, …, y, z 為表達(dá)式,op1, op2, …, opN為比較操作符灵汪,則
a op1 b op2 c … y opN z 等同于?a op1 b and b op2 c and … y opN z檀训,注:每一個(gè)表達(dá)式可獲取多次相同的值
5. 測試如下:
# Python code to illustrate
# chaining comparison operators
x = 5
print(1 < x < 10)? ? # True
print(10 < x < 20 )? # False
print(x < 10 < x*10 < 100)???# True
print(10 > x <= 9)? ?# True
print(5 == x > 4)? ?# True
a, b, c, d, e, f = 0, 5, 12, 0, 15, 15
print(a <= b < c > d is not e is f)? # True
print(a is d > f is not c)? # False
翻譯來源:https://www.geeksforgeeks.org/chaining-comparison-operators-python/