在python中创建对象列表
我正在尝试创建一个测验,第2个元素的在python中创建对象列表,python,arrays,object,Python,Arrays,Object,我正在尝试创建一个测验,第2个元素的问题数组中有语法错误。我尝试过通过` for循环将每个对象附加到数组中,但我需要每个问题都有一个正确的答案 问题类位于不同的文件中: class Questions: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer 以下是主文件: from Questions import Questions questions
问题数组中有语法错误。我尝试过通过` for循环将每个对象附加到数组中,但我需要每个问题都有一个正确的答案
问题类位于不同的文件中:
class Questions:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
以下是主文件:
from Questions import Questions
questionsPrompt = ["What does CPU stand for?\n(a) central procesing unit\n(b)controlled purification\n(c)computer unit",
"What is an advantage of a compiler?\n(a)slow to run each time\n(b)compiling takes a long time\n(c)easy to implement",
"The Operating System is a :\n(a)system software\n(b)application software\n(c)utility software"]
questions = [
Questions(questionsPrompt[0], "a")
Questions(questionsPrompt[1], "b")
Questions(questionsPrompt[2], "a")
]
def runQuiz(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer == question.answer:
score += 1
return score
runQuiz(questions)
正如Aran Fey指出的,您的语法不正确
questions = [
Questions(questionsPrompt[0], "a"),
Questions(questionsPrompt[1], "b"),
Questions(questionsPrompt[2], "a")
]
另外,还有一点,您要创建的是列表,而不是数组。语义和实现都有差异,因为Python两者都有,这是一个重要的区别。正如Aran Fey所评论的,列表项必须用逗号分隔。对于字典、集合等其他集合也是如此
questions = [
Questions(questionsPrompt[0], "a"),
Questions(questionsPrompt[1], "b"),
Questions(questionsPrompt[2], "a")
]
列表元素必须用逗号分隔,然后用循环和正确答案的列表或口述来完成。我犯了一个愚蠢的错误。数组和列表之间的区别是什么?可以在python文档网站上找到一个非常简短的摘要,网址是“此模块定义一种对象类型,它可以紧凑地表示基本值数组:字符、整数、浮点数。数组是序列类型,除了存储在其中的对象类型受到约束外,其行为非常类似于列表。“然而,列表可以包含任何对象,并且具有不同的方法集。请看这里: