You need to enable JavaScript to run this app. 基于list of dictionaries的Python问答游戏代码问题修复咨询
优惠活动
大模型
产品
解决方案
定价
更多

基于list of dictionaries的Python问答游戏代码问题修复咨询

Python问答小游戏代码修复方案

问题原因说明

  • 打印完整字典:循环内直接打印字典对象i,未单独提取question字段输出
  • 取值报错:循环变量i是列表中存储的单题字典对象,不是列表索引,且Python字典无value属性,无法通过qa.value[i]方式读取对应值,同时原代码存在多余的嵌套判断逻辑

修复后的顺序遍历代码

qa = [
    {"question": "Am I a dog?", "yes": "bark", "no": "what am I?"},
    {"question": "Are you a lion?", "yes": "growl?", "no": "Am I an elephant?"},
    {"question": "Am I a person?", "yes": "speak?", "no": "Am I an animal"},
    {"question": "Am I winter?", "yes": "snow?", "no": "Am I summer"}
]

user1 = []

for item in qa:
    # 仅输出题目文本
    print(item['question'])
    answer1 = input("enter 'yes' or 'no'.\n").lower()
    if answer1 == 'yes':
        user1.append('yes')
        res = item['yes']
        print(res)
        user1.append(res)
    elif answer1 == 'no':
        user1.append('no')
        res = item['no']
        print(res)
        user1.append(res)
    else:
        print("error")
print(user1)

随机遍历实现方法

如果需要打乱题目顺序随机出题,只需导入random模块,在遍历前打乱qa列表即可:

import random
# 打乱题目列表顺序
random.shuffle(qa)
# 后续遍历逻辑和上述顺序遍历代码完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 16:06:08