首页 > 解决方案 > 使用字符串访问数组中元素的索引,但字符串是随机选择的

问题描述

我正在制作一个文字冒险游戏,你必须在其中解谜。我创建了一个数组riddles = ["riddle1", "riddle2", ...]answers= ["answer1", "answer2", ...](答案 1 是谜语 1 的答案)然后我选择随机谜语,riddle = random.choice(riddles) 现在我检查是否inputanswer随机选择的谜语相同。但首先我尝试将随机选择的谜语的正确答案保存到变量answer中。我用answer = answers[riddle]. 我也尝试过answer = answers['riddle']在谷歌上找到的。我什至尝试过answer = answers[riddles[riddle]],我无法得到我想要的效果

list indices must be integers or slices, not str当我尝试运行程序时,我也会收到此错误

这是功能

`def谜语房间1():

riddles=["What has six faces, but does not wear makeup, has twenty-one eyes, but cannot see? What is it?", 
         "I am not alive, but I grow; I don't have lungs, but I need air; I don't have a mouth, but water kills me. What am I?",
        "What runs around the whole yard without moving?",
       "I am something people love or hate. I change peoples appearances and thoughts. If a person takes care of them self I will go up even higher. To some people I will fool them. To others I am a mystery. Some people might want to try and hide me but I will show. No matter how hard people try I will Never go down. What am I?"]
answers=["dice", "fire", "fence" ,"age"]

riddle = random.choice(riddles)
answer = answers[riddles[riddle]]
print(riddle)


guess = input("Your guess: ")

if guess == answer:
    print("Success, you can go forward. Which doors do you pick next (l or r)")
    answer = input(">").lower()
    if "r" in answer:
        riddle_room2()
    elif "l" in answer:
        safe_room2()
    else:
        game_over("You were messing around, and now your dead!")`

标签: pythonarraysindexing

解决方案


riddle = random.choice(riddles) 

你确定riddle这里是一个整数吗?要在下一行中使用谜语,它必须是整数。列表索引必须始终为整数。

answer = answers[riddles[riddle]]

我认为字典在这里会更有用。


推荐阅读