为了账号安全,请及时绑定邮箱和手机立即绑定

我的列表索引超出范围,我不知道该怎么办

我的列表索引超出范围,我不知道该怎么办

隔江千里 2022-12-20 14:42:29
我一直在尝试制作一个包含 2 个列表的程序。第一个列表是问题,其中存储了我必须将它们与用户输入进行比较的数据。如果用户输入与列表(问题)中的项目完全相同,则打印第二个列表中的其他数据。例如:Questions=["hello","yellow","horse"]Ans=["world","I pref red","I pref dog"]# now if input of user is something from the Questions list, it will print # from Ans# if input --> yellow# then --> print(Ans[1])我写的代码是这样的:x = len(Questions)leng = int(x / 2)quest = str(input('Which your question: '))while(quest!='@'):    counter = 0    if(quest == Questions[counter]):        print(Ans[counter])    else:        counter+=1        while(quest != Questions[counter] and counter<x):            counter+=1    print(Ans[counter])    quest = str(input('Which your question: '))出于某种原因,我出现了这个错误:list index out of range line 244, in while(quest != Questions[counter] and counter
查看完整描述

3 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

如果问题不在您的列表中,它将遍历列表,然后在尝试访问列表中不存在的元素时抛出超出范围的索引。


你能用字典吗?


questions = {

    "hello": "world",

    "yellow": "I pref red",

    "horse": "I pref dog"

}


quest = str(input('Which your question: '))


while (quest != '@'):

    if quest in questions:

      print(questions[quest])

    else:

      print("invalid input")

    quest = str(input('Which your question: '))

建议阅读一些关于字典的文档:


https://docs.python.org/3/tutorial/datastructures.html#dictionaries


https://realpython.com/python-dicts/


查看完整回答
反对 回复 2022-12-20
?
千万里不及你

TA贡献1784条经验 获得超9个赞

如果答案不在列表中,则counter==x(指的是不存在的元素)。


通常,不应使用并行列表,因为它们难以操作和维护。更好的解决方案是使用字典:


qAndA = {"hello" : "world", "yellow" : "I pref red", 

         "horse": "I pref dog"}

if quest in qAndA:

    print(qAndA[quest]) # Otherwise, repeat


查看完整回答
反对 回复 2022-12-20
?
暮色呼如

TA贡献1853条经验 获得超9个赞

您可以使用字典结构:


questions = {

    "hello": "world",

    "yellow": "I pref red",

    "horse": "I pref dog"

}


quest = ""


while quest != '@':

    quest = str(input('Which your question: '))

    answer = questions.get(quest, "I have no answer")

    print(answer)


查看完整回答
反对 回复 2022-12-20
  • 3 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信