我调用了一堆返回列表的方法。列表可能是空的。如果列表非空,我想返回第一项;否则,我想返回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
但是,在我看来,应该有一个简单的一行习语来做这件事。是吗?
当前回答
这个怎么样:
(my_list and my_list[0])或None
注意:这应该适用于对象列表,但它可能会返回错误的答案,在数字或字符串列表的情况下,每个下面的注释。
其他回答
(get_list() or [None])[0]
这应该有用。
顺便说一句,我没有使用变量列表,因为那会覆盖内置列表()函数。
编辑:我之前有一个稍微简单,但错误的版本。
try:
return a[0]
except IndexError:
return None
if mylist != []:
print(mylist[0])
else:
print(None)
我的用例只是设置一个局部变量的值。
就我个人而言,我发现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
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