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

标签 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]
        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')

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

关于python - 使用列表和文本文件的字符串索引超出范围错误(使用Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039229/

相关文章:

JavaScript split() 方法导致未定义

python - Jupyter Notebook 无法识别 "import torch"

python - 如果 x,y 在坐标框内

android - 使用 Retrofit 将 JsonArray 转换为 Kotlin 数据类(预期为 BEGIN_OBJECT 但为 BEGIN_ARRAY)

perl - 缓冲输出文件

c程序将ipconfig保存在文件中

python - 如何使用 TensorFlow 正确实现动态卷积神经网络

python - Numpy 在屏蔽后不会更改数组元素的值

java - Scala:从列表的列表创建结构(XML)

C++在遍历列表时从列表中删除