簡體   English   中英

如何解決我的代碼錯誤“列表索引超出范圍”

[英]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_int34 ,其是您的列表,它只有三個項目進行索引的范圍之外01 ,和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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM