如何访问Python字典特定数据?修正测验脚本输出标签错误
Python 选择题脚本:修正错误/正确答案的标签显示问题
你的问题出在错误提示部分误用了遍历字典后残留的label变量(该变量仅保留字典最后一个键的值),同时未正确映射正确答案对应的标签。以下是修正后的完整代码:
import random from string import ascii_lowercase NUM_QUESTIONS_PER_QUIZ = 5 QUESTIONS = { "This is question A": ["Choice 1", "Choice 2", "Choice 3"], "This is question B": ["Choice 1", "Choice 2", "Choice 3"], } num_questions = min(NUM_QUESTIONS_PER_QUIZ, len(QUESTIONS)) questions = random.sample(list(QUESTIONS.items()), k=num_questions) num_correct = 0 for num, (question, alternatives) in enumerate(questions, start=1): print(f"\nQuestion {num}:") print(f"{question}?") correct_answer = alternatives[0] # 生成带标签的选项字典 labeled_alternatives = dict(zip(ascii_lowercase, random.sample(alternatives, k=len(alternatives)))) # 创建反向字典:选项文本 -> 对应标签,用于快速查找正确答案的标签 alternative_to_label = {alt: lbl for lbl, alt in labeled_alternatives.items()} for label, alternative in labeled_alternatives.items(): print(f" {label}) {alternative}") while (answer_label := input("\nYour Choice? ")) not in labeled_alternatives: print(f"Please answer one of {', '.join(labeled_alternatives)}") answer = labeled_alternatives[answer_label] if answer == correct_answer: num_correct += 1 print("That is correct!") else: # 错误答案直接用用户输入的标签,正确答案通过反向字典匹配对应标签 print(f"Wrong Answer : {answer_label}) {answer}") print(f"Correct Answer: {alternative_to_label[correct_answer]}) {correct_answer}")
关键修正点:
- 新增反向字典
alternative_to_label:反转原标签字典的键值关系,实现通过选项文本快速定位对应标签,避免重复遍历查找。 - 替换错误提示的变量:
- 错误答案直接使用用户输入的
answer_label(即用户选择的选项标签),不再用循环残留的无效label变量。 - 正确答案通过反向字典
alternative_to_label[correct_answer]获取对应标签,保证显示与题目中的标签一致。
- 错误答案直接使用用户输入的
修正后输出示例:
Question 2: This is question A? a) Choice 1 b) Choice 2 c) Choice 3 Your Choice? b Wrong Answer : b) Choice 2 Correct Answer: a) Choice 1
内容的提问来源于stack exchange,提问作者DarCoy
相关产品推荐
相关产品推荐

