[英]implementing ternary operator in python using and/or combinations
我正在使用Mark Lutz的優秀著作來學習python。 我遇到了以下聲明,即python中的三元運算符,實際上是這樣的:
if a:
b
else:
c
可以用兩種方式編寫:
b if a else c
:使用python的普通三元語法,並且
((a and b) or c)
:使用等效但比較棘手的and/or
組合
我發現第二種表示方式令人不安,因為它與我的直覺並不吻合。 我在交互式提示上嘗試了這2種語法,並針對b = 0.
特殊情況找到了不同的答案。(假設b = 0,a = 4,c = 20)
0 if 4 else 20
輸出0
((4 and 0) or 20)
輸出20
看來,2個表達式是等效的所有truthy
的值b
,但不等同於所有falsy
的值b
。
我想知道,這里有什么我想念的。 我的分析錯了嗎? 為什么在書中這么說兩個案例是相等的。 請啟發我的粗心。 我是python的新手。 提前致謝。
沒錯,在大多數情況下,第二種方法很棒。
從python文檔中:
在Python 2.5中引入此語法之前,一個常見的習慣用法是使用邏輯運算符:[expression]和[on_true]或[on_false]
之后,他們提到:
“但是,這種習慣用法是不安全的,因為當on_true具有錯誤的布爾值時,它會產生錯誤的結果。因此,最好使用... if ... else ...形式。
這是參考: https : //docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-cs-ternary-operator
為每個請求添加簡要示例:
a = True
b = False
c = True
# prints False (for b) correctly since a is True
if a:
print b
else:
print c
# prints False (for b) correctly since a is True
print b if a else c
# prints True (for c) incorrectly since a is True and b should have been printed
print ((a and b) or c)
作者的觀點在這里是不同的,應該加以考慮。 讓我嘗試用代碼和內聯注釋來解釋:
#This if condition will get executed always(because its TRUE always for any number) except when it is '0' which is equivalent to boolean FALSE.
#'a' is the input which the author intends to show here. 'b' is the expected output
if a:
print(b)
else:
print(c)
#equivalent
print(b) if a else print(c)
print((a and b) or c)
您應該更改輸入並檢查輸出。 而您直接更改OUTPUT並嘗試檢查輸出,則該輸出不起作用。 因此,我認為您正在測試錯誤的方式。 輸入是一個。 這里的輸出是b。 情況1:b = 12 a = 1 c = 20
*Case 2:
b = 12
a = 0
c = 20*
*Dont change 'b'. Change only 'a' and test is the conceptual idea. Coz, 'b' is the output.*
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.