相关疑难解决方法(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中的'x = y或z'赋值是做什么的?

为什么我们看到Python分配or

例如:

def my_function(arg_1=None, arg_2=0):
    determination = arg_1 or arg_2 or 'no arguments given!'
    print(determination)
    return determination
Run Code Online (Sandbox Code Playgroud)

当没有参数调用时,上面的函数将打印并返回 'no arguments given!'

为什么Python会这样做,以及如何才能最好地利用此功能?

python boolean variable-assignment

6
推荐指数
1
解决办法
1997
查看次数

如何避免三元运算符赋值的重复?

从中获取大量配置值时os.environ,在python代码中使用默认值可以轻松地允许应用程序在许多上下文中启动.典型的django settings.py有很多

SOME_SETTING = os.environ.get('SOME_SETTING')
Run Code Online (Sandbox Code Playgroud)

线.

为了提供合理的默认值,我们选择了

SOME_SETTING = os.environ.get('SOME_SETTING') or "theValue"
Run Code Online (Sandbox Code Playgroud)

但是,由于调用应用程序,这很容易出错

SOME_SETTING="" 
Run Code Online (Sandbox Code Playgroud)

manage.py

将导致SOME_SETTING设置为theValue而不是明确定义""

有没有办法在python中使用三元组分配值a = b if b else d而不重复b或将其分配给速记变量?

如果我们看一下,这就变得很明显

SOME_VERY_LONG_VAR_NAME = os.environ.get('SOME_VERY_LONG_VAR_NAME') if os.environ.get('SOME_VERY_LONG_VAR_NAME') else 'meh'
Run Code Online (Sandbox Code Playgroud)

能够做类似的事情会好得多

SOME_VERY_LONG_VAR_NAME = if os.environ.get('SOME_VERY_LONG_VAR_NAME') else 'meh'
Run Code Online (Sandbox Code Playgroud)

python

0
推荐指数
1
解决办法
61
查看次数