0

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

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。

4

3 回答 3

3

你有,i<=len(liste)但你列表的最后一个元素将出现在 index len(liste)-1,这意味着你会得到一个IndexError.

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

于 2014-12-12T14:17:32.617 回答
0

这里:

while i<=len(liste):

i可以等于len(liste)。它不应该。你必须使用i<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
于 2014-12-12T14:17:13.703 回答
0

你所要做的就是print i在你的循环中,你会很容易地看到它为什么会发生。

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

于 2014-12-12T14:21:29.607 回答