添加数字时处理无

mic*_*mes 4 python nonetype

我想添加2个整数,也可以是None,结果如下:

add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b
Run Code Online (Sandbox Code Playgroud)

什么是最诡异,最简洁的表达方式?到目前为止,我有:

def add1(a, b):
    if a is None:
        return b
    elif b is None:
        return a
    else:
        return a + b
Run Code Online (Sandbox Code Playgroud)

要么

def add2(a, b):
    try:
        return a + b
    except TypeError:
        return a if a is not None else b
Run Code Online (Sandbox Code Playgroud)

有没有更短的方法来实现它?

Pau*_*zer 7

这相当紧凑,可以处理不同数量的术语:

def None_sum(*args):
    args = [a for a in args if not a is None]
    return sum(args) if args else None 
Run Code Online (Sandbox Code Playgroud)


Eri*_*nil 6

使用布尔逻辑:

这是一个 Pythonic 方法,使用 lazy or

def add(a, b):
    return (a or 0) + (b or 0)
Run Code Online (Sandbox Code Playgroud)

带过滤器

对于任意数量的被加数,您可以使用filterand sum

def add(*p):
    return sum(filter(None, p))

print(add(3))
# 3
print(add(3, 5))
# 8
print(add(3, 5, 7))
# 15
print(add(3, None))
# 3
print(add(None))
# 0
print(add(None, 0))
# 0
Run Code Online (Sandbox Code Playgroud)

有一个例外

请注意,之前的实现将返回0for add(None, None)。这是空和的预期数学结果。

返回None令人惊讶,TypeError当您使用add.

当用户没有输入任何有效的被加数时,实现所需行为的一种方法是抛出异常:

def add(*p):
    summands = list(filter(None, p))
    if not summands:
        raise ValueError("There should be at least one defined value.")
    return sum(summands)

print(add(3))
# 3
print(add(3, 5))
# 8
print(add(3, 5, 7))
# 15
print(add(3, None))
# 3
print(add(None, 0))
# 0
print(add(0))
# 0
print(add(None))
# ValueError: There should be at least one defined value
print(add())
# ValueError: There should be at least one defined value
Run Code Online (Sandbox Code Playgroud)