在c#中,有一个空合并操作符(写为??),允许在赋值时简单(短)检查空值:
string s = null;
var other = s ?? "some default value";
python中有等效的吗?
我知道我能做到:
s = None
other = s if s else "some default value"
但是有没有更短的方法(我不需要重复s)?
在c#中,有一个空合并操作符(写为??),允许在赋值时简单(短)检查空值:
string s = null;
var other = s ?? "some default value";
python中有等效的吗?
我知道我能做到:
s = None
other = s if s else "some default value"
但是有没有更短的方法(我不需要重复s)?
当前回答
除了Juliano关于“或”行为的回答之外: 这是“快速”
>>> 1 or 5/0
1
有时候这可能是一个有用的快捷方式
object = getCachedVersion() or getFromDB()
其他回答
处理可能的异常:
def default_val(expr, default=None):
try:
tmp = expr()
except Exception:
tmp = default
return tmp
像这样使用它:
default_val(lambda: some['complex'].expression('with', 'possible')['exceptions'], '')
如果你需要链接多个空条件操作,例如:
. data()模型?当代()
这不是一个容易解决的问题。它也不能用.get()来解决,因为它需要字典类型或类似的类型(并且无论如何都不能嵌套),也不能用getattr()来解决,当NoneType没有属性时,getattr()会抛出异常。
考虑向语言中添加空合并的相关PEP是PEP 505,与该文档相关的讨论在python-ideas线程中。
Python has a get function that its very useful to return a value of an existent key, if the key exist;
if not it will return a default value.
def main():
names = ['Jack','Maria','Betsy','James','Jack']
names_repeated = dict()
default_value = 0
for find_name in names:
names_repeated[find_name] = names_repeated.get(find_name, default_value) + 1
如果你在字典中找不到这个名字,它会返回default_value, 如果名称存在,则将任何现有值加1。
希望这能有所帮助
我知道这是有答案的,但是当您处理类似字典的对象时,还有另一种选择。
如果你有一个对象可能是:
{
name: {
first: "John",
last: "Doe"
}
}
你可以使用:
obj.get(property_name, value_if_null)
如:
obj.get("name", {}).get("first", "Name is missing")
通过添加{}作为默认值,如果“name”缺失,则返回一个空对象并传递给下一个get。这类似于c#中的null-safe-navigation,类似于obj?.name?.first。
我发现下面的两个函数在处理许多可变测试用例时非常有用。
def nz(value, none_value, strict=True):
''' This function is named after an old VBA function. It returns a default
value if the passed in value is None. If strict is False it will
treat an empty string as None as well.
example:
x = None
nz(x,"hello")
--> "hello"
nz(x,"")
--> ""
y = ""
nz(y,"hello")
--> ""
nz(y,"hello", False)
--> "hello" '''
if value is None and strict:
return_val = none_value
elif strict and value is not None:
return_val = value
elif not strict and not is_not_null(value):
return_val = none_value
else:
return_val = value
return return_val
def is_not_null(value):
''' test for None and empty string '''
return value is not None and len(str(value)) > 0