对于列表,除非在python中为空

Oli*_*Oli 23 python for-loop

在过去的几天里,我一直在编写很多这样的结构:

list = get_list()
if list:
    for i in list:
        pass # do something with the list
else:
    pass # do something if the list was empty
Run Code Online (Sandbox Code Playgroud)

很多垃圾和我将列表分配给一个真正的变量(将其保存在内存中的时间超过了需要).Python已经简化了我的很多代码直到现在......有一个简单的方法吗?

(我的理解是,elsefor: else:它循环,为空或不经过结构始终触发-所以不是我想要的)

Tom*_*eys 49

基于其他答案,我认为最干净的解决方案是

#Handles None return from get_list
for item in get_list() or []: 
    pass #do something
Run Code Online (Sandbox Code Playgroud)

或理解等价

result = [item*item for item in get_list() or []]
Run Code Online (Sandbox Code Playgroud)

  • 这是一个如此美丽的方式来做这个检查,太棒了! (2认同)

小智 9

使用列表理解:

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]
Run Code Online (Sandbox Code Playgroud)

  • 最后的"if list"是不必要的,并且针对每个项目进行评估,而不仅仅是一次. (11认同)
  • 你的理解不处理list = None (3认同)

Tri*_*ych 5

更轻微的是:

for i in my_list:
    # got a list
if not my_list:
    # not a list
Run Code Online (Sandbox Code Playgroud)

假设您没有更改循环中列表的长度.

来自Oli的编辑:为了弥补我对内存使用的担忧,它会想要with:

with get_list() as my_list:
    for i in my_list:
        # got a list
    if not my_list:
        # not a list
Run Code Online (Sandbox Code Playgroud)

但是,是的,围绕这个问题这是一个非常简单的方法.