返回第一项或非第一项的Python习惯用法

2024-04-25 23:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我相信有一种更简单的方法可以做到这一点,但我并没有想到。

我正在调用一组返回列表的方法。列表可能为空。如果列表非空,则返回第一项;否则,则不返回任何项。此代码有效:

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

在我看来,这样做应该有一个简单的单行成语,但对于我的生活,我想不起来。有?

编辑:

我在这里寻找单行表达式的原因并不是因为我喜欢非常简洁的代码,而是因为我必须编写很多这样的代码:

x = get_first_list()
if x:
    # do something with x[0]
    # inevitably forget the [0] part, and have a bug to fix
y = get_second_list()
if y:
    # do something with y[0]
    # inevitably forget the [0] part AGAIN, and have another bug to fix

我想做的当然可以通过一个函数来完成(而且可能会是):

def first_item(list_or_none):
    if list_or_none: return list_or_none[0]

x = first_item(get_first_list())
if x:
    # do something with x
y = first_item(get_second_list())
if y:
    # do something with y

我提出这个问题是因为我经常对Python中的简单表达式所能做的感到惊讶,我认为如果有一个简单的表达式可以做到这一点,那么编写一个函数是一件愚蠢的事情。但看到这些答案,似乎函数的简单解。


Tags: or函数代码列表getreturnif表达式
3条回答

最好的办法是:

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

您也可以在一行中完成,但程序员很难阅读:

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

Python2.6+

next(iter(your_list), None)

如果your_list可以是None

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

Python2.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

为了避免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
(get_list() or [None])[0]

这应该管用。

顺便说一下,我没有使用变量list,因为这会覆盖内置的list()函数。

编辑:我有一个稍微简单,但错误的版本在这里早些时候。

相关问题 更多 >