2015-10-04 13 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個元素被替換。這可能是一個字符串,因此在第012個元素後面調用(i+1)可能會導致Index out of range錯誤。

換句話說,這樣的事情正在發生:

i = 1
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" 

下一個循環週期將導致"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"] 

這也將是更Python的解決方案。