Python空列表异常

dde*_*blo 5 python exception except python-2.7

我有这个功能:

def foo():
    a = []
    if not a:
        print "empty"
        return None
    else:
        print "not empty"
        return a
Run Code Online (Sandbox Code Playgroud)

有没有做同样的例外?只是为了删除if条件.像这样的东西:

def foo(list):
    try:
        a = list
        return a
    except:
        return None
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 8

我会使用return l if l else None,你可以尝试索引列表,但我不会推荐它.

def foo(l):
    try:
        l[0]
        return l
    except IndexError:
        return None
Run Code Online (Sandbox Code Playgroud)

  • 最好不要只使用`except`,因为它可以隐藏意外错误.使用`除了IndexError`代替. (3认同)