列表索引超出范围 - Python

3
def Task4():
     import random
     t = True
     list1 = []
     list2 = []
     rand = random.randint(1,6)
     list1.append(rand)
     print(list1)
     for x in range(0,5):
         if list1[0] == (rand):
             list1.pop(0)
         else:
             list2.append(rand)
             print(list2)
             list1.pop(0)

无法理解为什么 if list1[0] == (rand) 会一直出现“列表索引超出范围”的错误。

在索引列表之前,您需要检查第一个元素是否存在(即列表不为空)-> if list1 and list1[0] == rand - grc
调试你的代码,你就会知道原因。你可以使用铅笔和纸来进行调试。 - Maroun
你只向list1添加了一个元素,但在循环中你尝试弹出5个元素。 - Andrew
3个回答

3

让我们看看list1会发生什么:

list1 = []

好的,列表已创建,但是它是空的。

rand = random.randint(1,6)
list1.append(rand)

rand被添加到列表中,因此此时list1 = [rand]

for x in range(0,5):

这将循环四次;因此,让我们看一下第一次迭代:
if list1[0] == (rand):

因为 list1 = [rand],所以 list1[0]rand。所以这个条件是真的。

list1.pop(0)

索引为0的列表元素被删除了;因为list1只包含一个元素(rand),所以现在它又变为空了。

for x in range(0,5):

循环的第二次迭代,x1

if list1[0] == (rand):

list1仍然为空,因此在列表中没有索引0。因此,这会崩溃并抛出异常。


此时,我很想告诉您如何更好地解决任务,但是您没有说明您要做什么,所以我只能给您一个提示:

当您从列表中删除项目时,只需迭代包含元素数量的次数。您可以使用while len(list1)循环(它将循环直到列表为空),或通过显式循环遍历索引for i in len(list1)来实现。当然,您也可以避免从列表中删除元素,并直接使用for x in list1循环遍历项目。


0
  • 当 x 为 0 时: -> 你弹出了唯一存在的列表项,因此列表在此之后为空

  • 当 x 为 1 时: -> 你尝试访问 list1[0],但它不存在 -> 列表索引超出范围错误


亲爱的Downvoter,我对改进我的答案很感兴趣,因此:您为什么要downvote这个答案?是的,它肯定可以更完整,但考虑到这是一个简单的问题,我认为简单的答案就足够了。 - DonCristobal
1
我认为你的回答非常完美。我也很好奇为什么会被踩。无论如何,我点了个赞。 - Stefan Pochmann

0
truth is evident with debugging with print and try except:

def Task4():
    import random
    t = True
    list1 = []
    list2 = []
    rand = random.randint(1,6)
    list1.append(rand)
    for x in range(0,5):
        try:
            print("list1 before if and pop",list1)
            if list1[0] == (rand):
                list1.pop(0)
                print("list1 after pop",list1)
            else:
                list2.append(rand)
                print("list2 {}".format(list2))
                list1.pop(0)
        except IndexError as e:
            print("Index Error {}".format(e))
            break

Task4()


list1 before if and pop [3]
list1 after pop []
list1 before if and pop []
Index Error list index out of range

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接