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

时间:2009-10-07 12:43:07

标签: for-loop python

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

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已经简化了很多我的代码直到现在......有一种简单的方法可以做到这一点吗?

(我的理解是else构造中的for: else:总是在它循环之后触发,空或不 - 所以不是我想要的那样)

7 个答案:

答案 0 :(得分:45)

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

#Handles None return from get_list
for item in get_list() or []: 
    pass #do something

或理解等值

result = [item*item for item in get_list() or []]

答案 1 :(得分: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]

答案 2 :(得分: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

但是,这是解决问题的一种简单方法。

答案 3 :(得分:2)

def do_something_with_maybe_list(maybe_list):
    if maybe_list:
        for x in list:
            do_something(x)
    else:
        do_something_else()

do_something_with_maybe_list(get_list())

您甚至可以提取要执行的操作:

def do_something_with_maybe_list(maybe_list, process_item, none_action):
    if maybe_list:
        for x in list:
            process_item(x)
    else:
        none_action()

do_something_with_maybe_list(get_list(), do_something, do_something_else)
do_something_with_maybe_list(get_otherlist(), do_other, do_still_other)

来自Oli的编辑:或者更进一步:

def do_something_with_maybe_list(maybe_list, process_item, none_action):
    if maybe_list:
        return process_list(maybe_list)
    return none_action()

do_something_with_maybe_list(get_list(), do_something, do_something_else)
do_something_with_maybe_list(get_otherlist(), do_other, do_still_other)

答案 4 :(得分:2)

如果您的行为不同,我会这样做:

list_ = get_list() # underscore to keep built-in list
if not list_:
    # do something
for i in list_: #
    # do something for each item

如果你的行为相似,那就更美了:

for i in list_ or [None]:
   # do something for list item or None

或者,如果您可能将None作为列表元素,

for i in list_ or [...]:
   # do something for list item or built-in constant Ellipsis

答案 5 :(得分:1)

我认为你的方式在一般情况下是可以的,但你可以考虑这种方法:

def do_something(item):
   pass # do something with the list

def action_when_empty():
   pass # do something if the list was empty

# and here goes your example
yourlist = get_list() or []
another_list = [do_something(x) for x in yourlist] or action_when_empty()

答案 6 :(得分:-1)

i = None
for i in get_list():
    pass # do something with the list
else:
    if i is None:
        pass # do something if the list was empty

这有帮助吗?是的,我知道距离需要还有两年的时间: - )