gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:08 25 4
gpt4 key购买 nike

我开发了一个程序,可以将用户的用户名、主题、单位、分数和成绩放入一个文本文件中。这是代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com