2015-10-04 2 views
0

У меня есть пустой список, (r) и объявил первый элемент в r[0] = aIndexError: Python список индексов вне диапазона

import time, urllib.request,random 

def getDictionary(): 
    word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain" 
    response = urllib.request.urlopen(word_site) 
    txt = response.read() 
    return txt.splitlines() 

def getWordsList(listOfWords, sample): 
    word = "" 
    randWords = [] 
    for i in range(0,sample): 
     while(len(word) <=2): 
      word = random.choice(listOfWords).decode('utf-8') 
     randWords.append(word) 
     word = "" 
    return randWords 
start = True 
noOfWords = 25 

words = getDictionary() 
wordsList = getWordsList(words, noOfWords) 

start = True 

print ("\nINSTRUCTIONS\nWhen the coundown gets to zero, type the word in lowercase letters!\n That's the only rule!") 
name = input("What is your name? ") 
name = name.split(" ") 
input("Press enter when ready...") 

while start == True: 

    print("Game will start in: ") 
    print ("3 seconds") 
    time.sleep(1) 
    print ("2 seconds") 
    time.sleep(1) 
    print ("1 seconds") 
    time.sleep(1) 

    times = [] 
    k = list() 
    r = list() 
    for i in range(25): 
     startTime = time.time() 
     userWord = input(str(i+1) + ". " + wordsList[i].capitalize() + " ") 
     k.append(wordsList[i].capitalize()) 
     if (userWord.lower() == wordsList[i].lower()): 
      endTime = time.time() 
      times.append(endTime - startTime) 
      r[i] = str(endTime - startTime)   
     else: 
      times.append("Wrong Word") 
      r[i] = ("Wrong Word") 

Выше, где у меня возникли проблемы.

for i in range(25): 
    startTime = time.time() 
    print (str(i+1) + ". " + str(k[i]) + ": " + str(times[i])) 
a = 0 
for i in range(25): 
    a = a+i 
for i in range(25): 
    if r[i] == "Wrong Word": 
     r = r.pop(i) 
b = (a/len(r)) 
c = round(b, 2) 
print (c) 
start = False 

здесь моя ошибка:

r[i] = "Wrong Word" 
IndexError: list assignment index out of range 

ответ

0

Метод pop() удаляет элемент из списка и returnes его (см an example). Я считаю, что в какой-то момент состояние статута if разрешается до true. Затем, после вызова r.pop(i)r заменяется на его i-й элемент. Вероятно, строка, вызывающая ее (i+1)-й элемент позже, может привести к ошибке Index out of range.

Другими словами, что-то подобное происходит:

r = ["a", "foo", "bar", "baz"] 
for i in range(4): 
    if r[i] == "a": # for i=0 this gives "a" == "a" 
     r = r.pop(i) # later,this results in r = "a" 

следующей итерации цикла с i = 1 приведет к "a"[1], что приведет к Index out of range.


В целом вместо:

for i in range(25): 
if r[i] == "Wrong Word": 
    r = r.pop(i) 

вы могли бы просто написать:

r = [item for item in r if item != "Wrong word"] 

, который будет также более вещим решением.

Смежные вопросы