編輯:它的回答,我不明白什么是三元運算子。對于未來有類似問題的人:https : //book.pythontips.com/en/latest/ternary_operators.html
我正在研究 python 中的“斷言”陳述句,但我不明白下面的句子。
assert .. if ... else ... and ...
因此,如果我理解正確,如果您想測驗“if else”陳述句,則必須使用上述內容。您必須在“if”陳述句之后立即插入以下內容: assert (P1 if E else P2) 和 E
例如
assert (y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
如果理解assert y == builtins.max(x,y)
它只是檢查條件是否為真,當它不為真時,它回傳一個斷言錯誤。但是,在以下情況下:
assert (y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
我不知道發生了什么。它顯然也總是回傳 true 。但我什至無法猜測到底發生了什么。我assert <condition>,<error message>查了一下 assert 陳述句的作用,它唯一做的就是:檢查條件并可能回傳錯誤訊息。但是我不明白... if ... else ... and ...條件如何。我明白,and但你如何準確地解釋if else在這種情況下的部分?
我真的不明白我不明白的事情。這可能是非常微不足道的。希望有人可以幫助我。抱歉我的拼寫錯誤。
編輯:它的回答,我不明白什么是三元運算子。對于未來有類似問題的人:https : //book.pythontips.com/en/latest/ternary_operators.html
uj5u.com熱心網友回復:
這里發生的是三元的斷言。
這個:
(y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
在概念上是:
A if cond else B # and cond2, but we'll come to that
它首先評估為 A 或 B。然后我們斷言,所以
assert A if cond else B
是相同的
x = A if cond else B
assert x
這個特殊的三元并不簡單。這相當于:
if x < y:
res = y == builtins.max(x, y)
else:
res = x == builtins.max(x,y)
assert res and x < y
恕我直言,這是相當不清楚。無論如何,這很有趣,因為在大多數情況下,您可以只做max()而不是builtins.max(). 也許它屬于一個測驗,或者一個max()(不明智地)被覆寫的背景關系?[想通了這大概是一種考驗builtins.max吧?]
參考
有關 python 的三元結構的更多資訊,請參見例如這個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/357375.html
