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

我一直在尝试制作一个包含 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


隔江千里
浏览 187回答 3
3回答

慕桂英3389331

如果问题不在您的列表中,它将遍历列表,然后在尝试访问列表中不存在的元素时抛出超出范围的索引。你能用字典吗?questions = {&nbsp; &nbsp; "hello": "world",&nbsp; &nbsp; "yellow": "I pref red",&nbsp; &nbsp; "horse": "I pref dog"}quest = str(input('Which your question: '))while (quest != '@'):&nbsp; &nbsp; if quest in questions:&nbsp; &nbsp; &nbsp; print(questions[quest])&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; print("invalid input")&nbsp; &nbsp; quest = str(input('Which your question: '))建议阅读一些关于字典的文档:https://docs.python.org/3/tutorial/datastructures.html#dictionarieshttps://realpython.com/python-dicts/

千万里不及你

如果答案不在列表中,则counter==x(指的是不存在的元素)。通常,不应使用并行列表,因为它们难以操作和维护。更好的解决方案是使用字典:qAndA = {"hello" : "world", "yellow" : "I pref red",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"horse": "I pref dog"}if quest in qAndA:&nbsp; &nbsp; print(qAndA[quest]) # Otherwise, repeat

暮色呼如

您可以使用字典结构:questions = {&nbsp; &nbsp; "hello": "world",&nbsp; &nbsp; "yellow": "I pref red",&nbsp; &nbsp; "horse": "I pref dog"}quest = ""while quest != '@':&nbsp; &nbsp; quest = str(input('Which your question: '))&nbsp; &nbsp; answer = questions.get(quest, "I have no answer")&nbsp; &nbsp; print(answer)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python