在C#中有一个null-coalescing运算符(写为??),允许在赋值期间进行简单(短)空检查:
string s = null;
var other = s ?? "some default value";
Run Code Online (Sandbox Code Playgroud)
是否有python等价物?
我知道我能做到:
s = None
other = s if s else "some default value"
Run Code Online (Sandbox Code Playgroud)
但是有更短的方式(我不需要重复s)?
许多语言的三元运算符都是这样的:
x = f() ? f() : g()
Run Code Online (Sandbox Code Playgroud)
其中if f()为truthy则x赋值为f(),否则赋值为g().但是,某些语言有一个更简洁的elvis运算符,它在功能上是等价的:
x = f() ?: g()
Run Code Online (Sandbox Code Playgroud)
在python中,三元运算符表达如下:
x = f() if f() else g()
Run Code Online (Sandbox Code Playgroud)
但是python有更简洁的elvis操作符吗?
也许是这样的:
x = f() else g() # Not actually valid python
Run Code Online (Sandbox Code Playgroud)