0

我有一个空列表 ( r) 并将第一个元素声明为r[0] = a

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
4

1 回答 1

0

pop()方法从列表中删除一个元素并将其返回(参见示例)。我认为正在发生的是,在某些时候,if语句的条件解析为true. 接下来,在调用之后r.pop(i) r被它的i第-个元素替换。它可能是一个字符串,因此稍后调用它的(i+1)-th 元素可能会导致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"

下一个循环迭代 withi = 1将导致"a"[1]which 将导致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"]

这也是更pythonic的解决方案。

于 2015-10-08T20:48:41.020 回答