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

Python遍历字典打印问答题目 为选项添加A/B/C/D前缀方法

实现代码

你原代码有两处问题:一是循环遍历的对象写了未定义的q,实际应该遍历questions字典;二是输出选项时没有拼接对应字母前缀。
直接用enumerate拿到选项的索引,从大写字母A的ASCII码开始累加,就能自动生成A、B、C、D的序号前缀,完整可运行代码如下:

questions ={
    '1.Who is Satoshi Nakamoto' : {'answers':{'right_answer':'Pseudonym','wrong_answer':['Bill Gate', 'Elon Musk', 'Warren Buffet']}},
    '2.Who is richest' : {'answers':{'right_answer':'Pseudonym','wrong_answer':['Bill Gate', 'Elon Musk', 'Warren Buffet']}}
}

for question in questions:
    print(question)
    # 拼接正确答案和错误答案得到完整选项列表
    answers = [questions[question]['answers']['right_answer']] + questions[question]['answers']['wrong_answer']
    for index, answer in enumerate(answers):
        # 索引0对应A,1对应B,以此类推
        option_tag = chr(ord('A') + index)
        print(f"{option_tag}.{answer}")
    # 不同题目之间输出空行,和预期格式对齐
    print()

运行输出

执行代码后会得到你想要的格式效果:

1.Who is Satoshi Nakamoto
A.Pseudonym
B.Bill Gate
C.Elon Musk
D.Warren Buffet

2.Who is richest
A.Pseudonym
B.Bill Gate
C.Elon Musk
D.Warren Buffet
  • 扩展提示:如果后续题目选项超过4个,该逻辑会自动顺延生成E、F等字母序号,不需要额外调整。如果要避免正确答案固定在A选项,可以在遍历选项前导入random模块后调用random.shuffle(answers)打乱选项顺序。

内容的提问来源于stack exchange,提问作者Jonathan Zimmermann

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:24:16