遍历列表,除非为空?
这几天我写了很多这样的代码:
list = get_list()
if list:
for i in list:
pass # do something with the list
else:
pass # do something if the list was empty
里面有很多多余的东西,我把这个列表赋值给一个真正的变量(这样会让它在内存中停留的时间比需要的长)。到目前为止,Python简化了我很多代码……有没有简单的方法可以做到这一点?
我理解的是,在 for: else:
这个结构中,else
总是在循环结束后触发,不管循环是空的还是有内容——这不是我想要的效果。
7 个回答
5
稍微简洁一点的是:
for i in my_list:
# got a list
if not my_list:
# not a list
假设你在循环中没有改变列表的长度。
Oli补充:为了考虑我的内存使用担忧,应该使用with
:
with get_list() as my_list:
for i in my_list:
# got a list
if not my_list:
# not a list
不过,是的,这确实是解决这个问题的一个简单方法。
86
根据其他人的回答,我觉得最简单明了的解决方案是
#Handles None return from get_list
for item in get_list() or []:
pass #do something
或者用理解式的写法
result = [item*item for item in get_list() or []]
12
使用列表推导式:
def do_something(x):
return x**2
list = []
result = [do_something(x) for x in list if list]
print result # []
list = [1, 2, 3]
result = [do_something(x) for x in list if list]
print result # [1, 4, 9]