C 和 Python 三元运算符之间的区别

Difference Between C and Python Ternary Operators

好吧,我刚读了一个 SOF 线程,我看到很多人都在谈论 Python 的三元运算符。我不知道 Python 有一个等效的三元运算符(三元运算符或条件表达式,无论你觉得舒服)。所以Python三元运算符的语法是...

play_golf if sun_shines else stay_dumb

此处Python将测试if之后的块sun_shines。如果块 returns true 它将在 if 之前执行块 play_golf 否则 Python 将在 else.

之后执行块 stay_dumb

另一方面,我想 C 的三元运算符更具可读性。

sun_shines ? play_golf : stay_dumb

好像在问问题sun_shines?真的?好的然后 play_golf 否则 stay_dumb.

现在我的问题是...

编辑: 我想我得到了第二个问题的答案...

Python: true if true else false

C: true ? true : false

Now my questions are...

How Python is more Pythonic here? "Simple is better than complex" failed here in my opinion. If I am wrong please clarify me. I want to know what I am missing?

英文句子是

如果天气好我们就去海边,否则我们就呆在家里

突出显示正确的词,省略填充词:

gotobeach if weather == "nice" else stayathome

看起来很像有效 Python ;)

Execution order of C and Python conditional expression is completely different I see.

没有。不是。

首先,分析行,然后计算 if 之后的条件,然后计算其中一个语句。

摘自定义条件表达式的PEP 308

Many C-derived languages use this syntax:

<condition> ? <expression1> : <expression2>

Eric Raymond even implemented this. The BDFL rejected this for several reasons: the colon already has many uses in Python (even though it would actually not be ambiguous, because the question mark requires a matching colon); for people not used to C-derived language, it is hard to understand.

在PEP中你可以找到决定的动机,我觉得合适,但这只是个人意见。

正如@Marcus Muller 所说,解析顺序与 C 没有区别。