首页 > 解决方案 > IndexError:尝试循环遍历 python 列表时出现错误

问题描述

我正在用python(和子弹模块)制作一个测验应用程序,所以我面临以下问题......

我正在尝试遍历列表并通过为索引生成从 0 到 len(list)+1 的随机数来创建类的对象。它抛出索引错误:

代码:questionlist.py

from question import Question
from random import randint

# Question(text, option1, option2, option3, option4, answer)

texts = [
 "Which website is mostly used to search for errors in a piece of code (or anything related to software engineering)?",
 "Which of the following companies has developed and is maintaining React JS?",
 "What is 'M' in MERN Stack?",
 "Which of the following is 'not' a programming language?",
 "Which of the following is 'not' used for Machine Learning"
]

option1_s = [
 "Reddit",
 "Google",
 "MariaDB",
 "Redis",
 "Keras",
]

option2_s = [
 "Stackoverflow",
 "Mozilla"
 "MongoDB",
 "Java",
 "Tensorflow",
]

option3_s = [
 "Stackexchange",
 "Twitter",
 "MySQL",
 "Python",
 "PyTorch"
]

option4_s = [
 "Discord",
 "Facebook",
 "Memcached",
 "Assembly",
 "Postman",
]

answers = [
 "Stackoverflow",
 "Facebook",
 "MongoDB",
 "Redis"
]

def create_question_list(num_of_questions):
 questions = []
 

 for i in range(num_of_questions):
     
     index_number = randint(0, len(texts)+1)
     print(index_number)
     questions.append(
         Question(
             texts[index_number],
             option1_s[index_number],
             option2_s[index_number],
             option3_s[index_number],
             option4_s[index_number],
             answers[index_number]
         )
     )

 return questions

投掷

IndexError:列表索引错误超出范围

还有2个文件,但这个文件中存在错误,但如果有人想回答,你还需要检查其他2个代码,它们是:https ://github.com/codingdsb/Python-Quiz -应用程序/

请尽快回答

标签: python

解决方案


首先,如果您不上课,请不要回答一件事。

问题是您的答案编号高于某些问题列表的长度:

运行项目链接:https ://replit.com/@batichico/quiz

你应该把index_number = randint(0, len(texts)-1)而不是index_number = randint(0, len(texts)+1)


推荐阅读