我确信有一种更简单的方法可以解决这个问题.
我正在调用一堆返回列表的方法.该列表可能为空.如果列表非空,我想返回第一个项目; 否则,我想要返回无.此代码有效:
my_list = get_list()
if len(my_list) > 0: return my_list[0]
return None
Run Code Online (Sandbox Code Playgroud)
在我看来,应该有一个简单的单行成语,但对于我的生活,我无法想到它.在那儿?
编辑:
我在这里寻找单行表达式的原因并不是因为我喜欢简洁的代码,而是因为我必须编写很多像这样的代码:
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
Run Code Online (Sandbox Code Playgroud)
我想要做的事情当然可以用一个函数来完成(也可能是):
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 …Run Code Online (Sandbox Code Playgroud)