我调用了一堆返回列表的方法。列表可能是空的。如果列表非空,我想返回第一项;否则,我想返回None。这段代码工作:

def main():
    my_list = get_list()
    if len(my_list) > 0:
        return my_list[0]
    return None

但是,在我看来,应该有一个简单的一行习语来做这件事。是吗?


当前回答

最好的方法是:

a = get_list()
return a[0] if a else None

你也可以在一行中完成,但这对程序员来说很难读懂:

return (get_list()[:1] or [None])[0]

其他回答

try:
    return a[0]
except IndexError:
    return None
def head(iterable):
    try:
        return iter(iterable).next()
    except StopIteration:
        return None

print head(xrange(42, 1000)  # 42
print head([])               # None

顺便说一句:我会把你的一般程序流程重做成这样:

lists = [
    ["first", "list"],
    ["second", "list"],
    ["third", "list"]
]

def do_something(element):
    if not element:
        return
    else:
        # do something
        pass

for li in lists:
    do_something(head(li))

(尽可能避免重复)

my_list[0] if len(my_list) else无

Python 2 + 6。

next(iter(your_list), None)

如果your_list可以为None:

next(iter(your_list or []), None)

Python 2.4

def get_first(iterable, default=None):
    if iterable:
        for item in iterable:
            return item
    return default

例子:

x = get_first(get_first_list())
if x:
    ...
y = get_first(get_second_list())
if y:
    ...

另一个选择是内联上面的函数:

for x in get_first_list() or []:
    # process x
    break # process at most one item
for y in get_second_list() or []:
    # process y
    break

为了避免中断,你可以这样写:

for x in yield_first(get_first_list()):
    x # process x
for y in yield_first(get_second_list()):
    y # process y

地点:

def yield_first(iterable):
    for item in iterable or []:
        yield item
        return

我的用例只是设置一个局部变量的值。

就我个人而言,我发现try and except风格更容易阅读

items = [10, 20]
try: first_item = items[0]
except IndexError: first_item = None
print first_item

而不是切片列表。

items = [10, 20]
first_item = (items[:1] or [None, ])[0]
print first_item