Python:从空列表中弹出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31216428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:39:01  来源:igfitidea点击:

Python: pop from empty list

pythonpython-2.7

提问by Karvy1

I am using below line in a loop in my code

我在我的代码中循环使用下面的行

importer = exporterslist.pop(0)

If exporterslist has no entries or it is null, it returns error: IndexError: pop from empty list. How can I bypass exporterslist with no entries in it?

如果 exporterslist 没有条目或有条目null,则返回error: IndexError: pop from empty list。如何绕过没有条目的exporterslist?

One idea I can think of is if exporterslist is not null then importer = exporterslist.pop(0)else get the next entry in the loop. If the idea is correct, how to code it in python?

我能想到的一个想法是,如果 exporterslist 不为 null,则importer = exporterslist.pop(0)获取循环中的下一个条目。如果想法是正确的,如何在python中对其进行编码?

采纳答案by NightShadeQueen

You're on the right track.

你在正确的轨道上。

if exporterslist: #if empty_list will evaluate as false.
    importer = exporterslist.pop(0)
else:
    #Get next entry? Do something else?

回答by Utsav T

Use this:

用这个:

if exporterslist:
    importer = exporterslist.pop(0)

回答by Padraic Cunningham

You can also use a try/except

您也可以使用 try/except

try:
    importer = exporterslist.pop(0)
except IndexError as e:
    print(e)

If you are always popping from the front you may find a dequea better option as deque.popleft() is 0(1).

如果您总是从前面弹出,您可能会发现deque是更好的选择,因为 deque.popleft() 是 0(1)

回答by Josh Woods

You can also .pop() only if the list has items in it by determining if the length of the list is 1 or more:

您也可以通过确定列表的长度是否为 1 或更多,仅当列表中有项目时 .pop() :

if len(exporterslist) > 1:
    importer = exporterslist.pop()

回答by Gergely M

This one..

这个..

exporterslist.pop(0) if exporterslist else False

exporterslist.pop(0) if exporterslist else False

..is somewhat the same as the accepted answer of @nightshadequeen's just shorter:

.. 与@nightshadequeen 的接受答案有些相同,只是更短:

>>> exporterslist = []   
>>> exporterslist.pop(0) if exporterslist else False   
False

or maybe you could use this to get no return at all:

或者也许你可以用它来获得任何回报:

exporterslist.pop(0) if exporterslist else None

exporterslist.pop(0) if exporterslist else None

>>> exporterslist = [] 
>>> exporterslist.pop(0) if exporterslist else None
>>>