相关疑难解决方法(0)

是否有C#null-coalescing运算符的Python等价物?

在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)?

python null-coalescing-operator

258
推荐指数
6
解决办法
7万
查看次数

Python有Elvis运算符吗?

许多语言的三元运算符都是这样的:

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)

python conditional-operator

9
推荐指数
2
解决办法
2757
查看次数