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



我一直在尝试制作一个带有 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: '))

出于某种原因,我正在接受此错误:列出索引超出范围第 244 行,在 而(任务!=问题[计数器]和计数器

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

你能用字典吗?

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/

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

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

qAndA = {"hello" : "world", "yellow" : "I pref red", 
"horse": "I pref dog"}
if quest in qAndA:
print(qAndA[quest]) # Otherwise, repeat

您可以使用字典结构:

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)

相关内容

最新更新