在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)?
当前回答
严格来说,
other = s if s is not None else "default value"
否则,s = False将成为“默认值”,这可能不是预期的。
如果你想让这段话更短,试试:
def notNone(s,d):
if s is None:
return d
else:
return s
other = notNone(s, "default value")
其他回答
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。
希望这能有所帮助
下面是一个函数,它将返回第一个非None的参数:
def coalesce(*arg):
return reduce(lambda x, y: x if x is not None else y, arg)
# Prints "banana"
print coalesce(None, "banana", "phone", None)
reduce()可能不必要地遍历所有参数,即使第一个参数不是None,所以你也可以使用这个版本:
def coalesce(*arg):
for el in arg:
if el is not None:
return el
return None
处理可能的异常:
def default_val(expr, default=None):
try:
tmp = expr()
except Exception:
tmp = default
return tmp
像这样使用它:
default_val(lambda: some['complex'].expression('with', 'possible')['exceptions'], '')
除了单个值的@Bothwells answer(我更喜欢这个),为了检查函数返回值的空值分配,你可以使用new walrus-operator(自python3.8以来):
def test():
return
a = 2 if (x:= test()) is None else x
因此,测试函数不需要计算两次(如果test()为None else test(),则a = 2)
如果你需要链接多个空条件操作,例如:
. data()模型?当代()
这不是一个容易解决的问题。它也不能用.get()来解决,因为它需要字典类型或类似的类型(并且无论如何都不能嵌套),也不能用getattr()来解决,当NoneType没有属性时,getattr()会抛出异常。
考虑向语言中添加空合并的相关PEP是PEP 505,与该文档相关的讨论在python-ideas线程中。