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

其他回答

如果你需要链接多个空条件操作,例如:

. data()模型?当代()

这不是一个容易解决的问题。它也不能用.get()来解决,因为它需要字典类型或类似的类型(并且无论如何都不能嵌套),也不能用getattr()来解决,当NoneType没有属性时,getattr()会抛出异常。

考虑向语言中添加空合并的相关PEP是PEP 505,与该文档相关的讨论在python-ideas线程中。

严格来说,

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。

希望这能有所帮助

对于那些像我一样跌跌撞撞地在这里寻找一个可行的解决方案,当变量可能是未定义的,我得到的最接近的是:

if 'variablename' in globals() and ((variablename or False) == True):
  print('variable exists and it\'s true')
else:
  print('variable doesn\'t exist, or it\'s false')

请注意,签入全局变量时需要字符串,但之后在检查value时使用实际变量。

关于变量存在的更多信息: 如何检查变量是否存在?

除了单个值的@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)