Python读取文本存入列表时多余空串及答案错存问题排查
问题解答
问题1:test_questions列表出现大量空字符串的原因
你定义的read_quest函数循环逻辑错误:
- 你当前的循环是遍历
file_read_q的每一行,也就是读取到多少行就会循环多少次,每次循环都会向test_questions追加一次内容 - 你的测试题库只有2道题,对应两次切片就能取完所有有效内容,后续循环的切片范围已经超出了读取到的行列表范围,
file_read_q[start:stop]返回空列表,join之后就得到空字符串,最终就出现大量空值。
正确做法是按每5行一组的步长循环,不要按行遍历。
问题2:答案被追加到test_questions列表的原因
你在read_answers函数里写错了追加的列表名,把本该追加到test_answers的内容错误写到了test_questions里,只需要把test_questions.append(i)改成test_answers.append(i)即可。
修复后可正常运行的代码
test_questions = [] test_answers = [] # 读取问题列表 def read_quest(): # 用with上下文管理器自动处理文件关闭,无需手动调用close with open("test_question_bank.txt", "r", encoding="utf-8") as bank: file_read_q = bank.readlines() # 按每5行一组遍历,避免无效循环 for start in range(0, len(file_read_q), 5): stop = start + 5 temp_q = "".join(file_read_q[start:stop]).strip() # 过滤空内容 if temp_q: test_questions.append(temp_q) # 读取答案列表 def read_answers(): with open("test_correct_ans.txt", "r", encoding="utf-8") as ans: file_read_a = ans.readlines() for i in file_read_a: i = i.strip("\n") # 修正追加的目标列表 if i: test_answers.append(i) # 新增题目函数 def add_quest(): prompt = input("Please write question: ") ansa = input("Write answer for choice a): ") ansb = input("Write answer for choice b): ") ansc = input("Write answer for choice c): ") correct_opt = input("Which option is the correct answer? ") temp_quest = f"{prompt}\n(a) {ansa}\n(b) {ansb}\n(c) {ansc}\n\n" with open("test_question_bank.txt", "a", encoding="utf-8") as bank: bank.write(temp_quest) with open("test_correct_ans.txt", "a", encoding="utf-8") as correct_ans: correct_ans.write(correct_opt + "\n") read_quest() read_answers() print(test_questions) print(test_answers) # add_quest()
内容的提问来源于stack exchange,提问作者Japs6901
相关产品推荐
相关产品推荐

