For 循环遍历列表除非空?

问题描述 投票:0回答:7

过去几天我写了很多这样的结构:

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:
总是在循环后触发,无论是否为空 - 所以不是我想要的)

python for-loop nonetype
7个回答
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]

5
投票

更简洁的是:

for i in my_list:
    # got a list
if not my_list:
    # not a list

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

Oli 的编辑:为了补偿我对内存使用的担忧,它需要

with
ing:

with get_list() as my_list:
    for i in my_list:
        # got a list
    if not my_list:
        # not a list

但是,是的,这是解决这个问题的一个非常简单的方法。


4
投票

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

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

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)

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()

0
投票
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

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

© www.soinside.com 2019 - 2024. All rights reserved.