[英]How to fix my code's error “List index out of range”
如何解决我的代码出现以下错误?
Traceback (most recent call last):
File "main.py", line 143, in <module>
print(question_list2[random_int])
IndexError: list index out of range
这是有问题的代码:
question_list2 = []
question_list2.append(" the marines are ___ based opreatives ")
question_list2.append(" for under water travel marines use _____ ")
question_list2.append(" the avergae marine trains for _ weeks ")
answer_list2 = []
answer_list2.append("sea")
answer_list2.append("subamrines")
answer_list2.append("13")
top_index = 4
correct = 0
for i in range (0,4):
random_int = random.randint(0,top_index)
print(question_list2[random_int])
top_index = top_index - 1
user_answer1 = input("fill in the blank with the correct word ")
if user_answer == answer_list1[random_int]:
correct = correct + 3
del question_list1[random_int]
del answer_list1[random_int]
来自随机文档
random.randint(a,b)
返回一个随机整数N,使得a <= N <= b
这意味着:
top_index = 4
random_int = random.randint(0,top_index)
具有设定的可能性random_int
至3
或4
,其是您的列表,它只有三个项目进行索引的范围之外0
, 1
,和2
。
与其更改列表并使用索引,不如创建一个索引列表,对其进行随机排序然后对其进行迭代,可能会更容易:
indexes = random.sample(range(0, len(question_list)), k = len(question_list))
for i in indexes:
# etc...
如果将问题和答案一起保存在一个列表中,则可以完全消除索引。 这对于命名元组将是一个很好的用途
import random
from collections import namedtuple
qa = namedtuple('QA', ['question', 'answer'])
question_list = [
qa(" the marines are ___ based opreatives ", 'sea'),
qa(" for under water travel marines use _____ ",'submarines'),
qa(" the avergae marine trains for _ weeks ", '13')
]
random.shuffle(question_list)
correct = 0
for qa in question_list:
print(qa.question)
user_answer = input("fill in the blank with the correct word ")
if user_answer == qa.answer:
correct = correct + 1
我相信您的清单上只有三件事。 范围应该是range(0,3),也许您的top_index应该是top_index = 2。
由于您列表上的索引为[0,1,2]
列表>索引= 0的第一项
列表>索引= 1中的第二项
列表>索引= 2的第三项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.