Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用列表和文本文件的字符串索引超出范围错误(使用Python)_Python_List_Text Files - Fatal编程技术网

使用列表和文本文件的字符串索引超出范围错误(使用Python)

使用列表和文本文件的字符串索引超出范围错误(使用Python),python,list,text-files,Python,List,Text Files,我开发了一个程序,将用户的用户名、主题、单位、分数和分数放入文本文件。代码如下: tests.extend([subject, unit, str(score), grade]) print tests with open("test.txt", "a") as testFile: for test in tests: userName = test[0] subject = test[1] unit = test[2]

我开发了一个程序,将用户的用户名、主题、单位、分数和分数放入文本文件。代码如下:

tests.extend([subject, unit, str(score), grade])
print tests

with open("test.txt", "a") as testFile:
    for test in tests:
        userName = test[0]
        subject = test[1]
        unit = test[2]
        score = test[3]
        grade = test[4]

        testFile.write(userName + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n')
它打印:

['abc', 'history', 'Nazi Germany', '65', 'C'] 
(“abc”是用户名)

以及以下错误:

grade = test[4]
IndexError: string index out of range
我不知道为什么会出现这个错误?有什么想法吗

*已在之前的测验中添加:*

quizzes = []  
quizzes.append(userName)

在for循环中,您迭代一个测试中的每个单词,而不是测试列表中的每个测试。 因此,当您调用test[0]或test[4]时,您并没有索引一个测试的特征,而是意外地从一个测试的特征中获取了一个字符。 您可以通过在测试数组周围放置括号来修复此问题。 例如:

Tests = [['abc', 'history', 'Nazi Germany', '65', 'C'],
         ['test2', 'python', 'iteration', '65', 'C']]
for username, subject, unit, score, grade in tests:
     testFile.write(username + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n')

现在,您正在迭代测试中的每个测试,而不是一个测试中的每个特性

好的,我编辑了,如果您还有问题,请回答EP,它现在正在工作。谢谢你的回答和解释!