【问题标题】:IndexError: list index out of range Why?IndexError: list index out of range 为什么?
【发布时间】:2015-02-11 06:35:14
【问题描述】:

我知道这个问题已经回答了很多次,但我不知道我的问题出在哪里。这是我的代码:

from random import*

def VerificationLongue():

    x=randint(0,1000)
    liste=CreerListe()
    Check=0
    i=0

    while i<=len(liste):
        if x==liste[i]:
            Check=Check+1
        i=i+1

    print("X est dans la liste",Check," fois")

def CreerListe(): 
    ListeAleatoire=[]
    for i in range (0,100):
        valeur=randint(0,1000)
        ListeAleatoire.append(valeur)
    return (ListeAleatoire)


VerificationLongue()

这是一个简单的算法,用于查找一个数字是否在随机数列表中。我知道有这样的“计数”或“输入”功能,但这是针对学校的,他们不希望我们使用它们。所以我得到了错误:

line 11, in VerificationLongue
    if x==liste[i]:
IndexError: list index out of range

不知道为什么会出现这个错误,因为初始化为0。

【问题讨论】:

  • while i&lt;=len(liste): - 如果i == len(liste), i 超出列表末尾

标签: python algorithm sorting search indexoutofrangeexception


【解决方案1】:

这里:

while i<=len(liste):

i 可以等于len(liste)。它不应该。你必须使用i&lt;len(liste):

>>> l = range(5)
>>> l
[0, 1, 2, 3, 4]
>>> len(l)
5
>>> l[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> l[4]
4

旁注:您可以使用理解来执行您的 while 循环:

>>> liste = [randrange(10) for _ in xrange(20)]
>>> liste
[4, 4, 0, 7, 6, 6, 2, 9, 8, 1, 4, 7, 2, 4, 1, 4, 7, 4, 0, 2]
>>> x=randint(0,10)
>>> x
4
>>> sum(x == i for i in liste)
6

但列表也有count 方法:

>>> liste.count(x)
6

【讨论】:

    【解决方案2】:

    您已获得i&lt;=len(liste),但列表的最后一个元素将出现在索引len(liste)-1,这意味着您将获得IndexError

    您可以通过将其替换为 i &lt; len(liste) 来解决此问题。

    【讨论】:

      【解决方案3】:

      您所要做的就是在您的循环中print i,您就会很容易看到它发生的原因。

      您的循环应该是i &lt; len(liste) 而不是&lt;=。列表从零开始索引,因此如果您有 100 个项目,它们的编号为 0-99。通过使用&lt;=,您将从0 到100,而liste[100] 不存在。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-28
        • 2019-02-23
        • 1970-01-01
        • 2019-04-15
        • 2020-10-16
        • 1970-01-01
        • 2016-04-21
        相关资源
        最近更新 更多