Python成语返回第一项或无 [英] Python idiom to return first item or None
问题描述
我敢肯定,有一种更简单的方法只是我不曾想到的.
I'm sure there's a simpler way of doing this that's just not occurring to me.
我正在调用一堆返回列表的方法.该列表可能为空.如果列表是非空的,我想返回第一项.否则,我想返回无.这段代码有效:
I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:
my_list = get_list()
if len(my_list) > 0: return my_list[0]
return None
在我看来,这样做应该有一个简单的单行成语,但就我的一生而言,我想不起来.有吗?
It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there?
我在这里查找单行表达式的原因并不是我喜欢令人难以置信的简洁代码,而是因为我不得不编写很多这样的代码:
The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:
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
我想做的事情肯定可以通过一个函数来完成(可能会做到):
What I'd like to be doing can certainly be accomplished with a function (and probably will be):
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中的简单表达式可以做什么感到惊讶,并且我认为编写一个函数是一件很愚蠢的事情,只要有一个简单的表达式就能解决问题.但是看到这些答案,似乎函数是的简单解决方案.
I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function is the simple solution.
推荐答案
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:
...
另一种选择是内联上述功能:
Another option is to inline the above function:
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
,您可以这样写:
To avoid break
you could write:
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
这篇关于Python成语返回第一项或无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!