使用字符串访问数组中元素的索引,但字符串是随机选择的

2024-05-18 17:42:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我试图运行程序时,我也会遇到这个错误list indices must be integers or slices, not str

下面是函数

'def ridle_room1():

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!")`

Tags: orand答案answerinputnotampeople
3条回答
riddle = random.choice(riddles) 

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

answer = answers[riddles[riddle]]

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

您得到错误是因为要从列表list[index]中获取某些内容,需要传递索引参数,该参数应为整数。但是您正在传递导致错误的字符串索引

现在是下一个问题的解决方案

要获得谜语所属的索引,您可以执行以下操作

answer = answers[riddles.index(riddle)]

index函数告诉给定参数的索引编号(参数是您在函数括号中给出的东西!)

例:

strs = ['hello','bye','welcome']
print(strs.index('bye')) #this will print 1 as strs[1] is bye

希望你得到了答案,如果有任何疑问,你可以发表评论

列表索引必须是整数

r = random.randint(0,len(riddles))
riddle = riddles [r]
answer = answers [r]

相关问题 更多 >

    热门问题