Для списка, кроме пустого в 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:
всегда запускается после того, как он зациклился, пуст или нет - так что не хочу)
Ответы
Ответ 1
Используйте понимание списка:
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
Основываясь на других ответах, я думаю, что самые чистые решения -
#Handles None return from get_list
for item in get_list() or []:
pass #do something
или понимание equiv
result = [item*item for item in get_list() or []]
Ответ 3
Немного сложнее:
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
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)
Отредактируйте с Оли: Или идите дальше:
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)
Ответ 5
Если ваши действия разные, я бы сделал:
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
Ответ 6
Я думаю, что ваш путь в общем случае в порядке, но вы можете рассмотреть этот подход:
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()
Ответ 7
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
Помогает ли это? Да, я знаю, что мы находимся на расстоянии двух лет от необходимости: -)