Python是否具有Elvis运算符? [英] Does Python have the Elvis operator?
问题描述
许多语言中的三元运算符的工作方式如下:
The ternary operator in many languages works like so:
x = f() ? f() : g()
如果 f()
是真实的,则为 x
赋值 f()
,否则为它赋值 g()
。但是,某些语言的 elvis 运算符更为简洁:
Where if f()
is truthy then x
is assigned the value of f()
, otherwise it is assigned the value of g()
. However, some languages have a more succinct elvis operator that is functionally equivalent:
x = f() ?: g()
在python中,三元运算符表示为:
In python, the ternary operator is expressed like so:
x = f() if f() else g()
但是python的 elvis 操作符更简洁?
But does python have the more succinct elvis operator?
也许像这样:
x = f() else g() # Not actually valid python
推荐答案
是
Python确实具有elvis运算符。它是条件或
运算符:
x = f() or g()
f()
。如果为真,则为x分配 f()
的值,否则为x分配 g()
的值。
f()
is evaluated. If truthy, then x is assigned the value of f()
, else x is assigned the value of g()
.
参考: https:/ /en.wikipedia.org/wiki/Elvis_operator#Analogous_use_of_the_short-circuiting_OR_operator
这篇关于Python是否具有Elvis运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!