索引错误:从空lis弹出

2024-04-28 10:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编写python相当陌生。。。尝试理解.pop()函数以及如何从列表中弹出一个项并追加到新列表。有人能帮我处理一下这段代码,看看它为什么告诉我我是从一个空列表中跳出来的吗?

more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 
new_list = []

while len(new_list) <= 8:
    stuff = more_stuff.pop() 
    print "Adding: ", stuff
    new_list.append(stuff)

print new_list

我在运行代码时得到这个结果:

Traceback (most recent call last):
  File "testpop.py", line 5, in <module>
    stuff = more_stuff.pop()
IndexError: pop from empty list

Tags: 函数代码列表newsongmorepoplist
3条回答

您应该在more_stuff列表中检查您的条件,因为这将耗尽项:

while len(more_stuff) > 0:
    ...

more_stuff为空时,len(more_stuff)=0pop()仍将工作。

使用list作为条件,如果列表为空,则bool值为False

more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana",
"Girl", "Boy"] 
new_list = []
while more_stuff:
    stuff = more_stuff.pop() 
    print ("Adding: ", stuff)
    new_list.append(stuff)

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a bool() or len() method, when that method returns the integer zero or bool value False.

列表中的索引从零开始。

所以,在more_stuff[7]中,你会得到最后一个。

您的代码试图在不存在的'Boy'之后弹出另一个元素。

你需要解决的是:

while len(new_list) <= 7:

编辑:

你也可以通过列表理解来完成:

more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana",
"Girl", "Boy"] 

new_list = [more_stuff.pop() for __ in xrange(len(more_stuff))]

print new_list

相关问题 更多 >