You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 23:20:04