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

其他回答

除了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'], '')
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

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