我调用了一堆返回列表的方法。列表可能是空的。如果列表非空,我想返回第一项;否则,我想返回None。这段代码工作:
def main():
my_list = get_list()
if len(my_list) > 0:
return my_list[0]
return None
但是,在我看来,应该有一个简单的一行习语来做这件事。是吗?
我调用了一堆返回列表的方法。列表可能是空的。如果列表非空,我想返回第一项;否则,我想返回None。这段代码工作:
def main():
my_list = get_list()
if len(my_list) > 0:
return my_list[0]
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))
(尽可能避免重复)
其他回答
坦率地说,我认为没有更好的成语了:your is clear and short -不需要什么“更好的”。也许吧,但这真的是一个品味的问题,你可以改变if len(list) > 0:与if list: -一个空列表将永远求值为False。
在相关的说明中,Python不是Perl(没有双关的意思!),您不必获得尽可能最酷的代码。 实际上,我在Python中见过的最糟糕的代码,也是非常酷的:-),而且完全无法维护。
顺便说一下,我在这里看到的大多数解决方案都不考虑list[0]计算为False(例如空字符串或零)-在这种情况下,它们都返回None而不是正确的元素。
try:
return a[0]
except IndexError:
return None
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
可能不是最快的解决方案,但没有人提到这个选项:
dict(enumerate(get_list())).get(0)
如果get_list()可以返回None,你可以使用:
dict(enumerate(get_list() or [])).get(0)
优点:
一线
-你只需要调用get_list()一次
-容易理解
(get_list() or [None])[0]
这应该有用。
顺便说一句,我没有使用变量列表,因为那会覆盖内置列表()函数。
编辑:我之前有一个稍微简单,但错误的版本。