繁体   English   中英

创建对象列表python

[英]Create a list of objects python

我正在尝试创建测验,并且第二个元素的questions数组中存在语法错误。 我试图通过`for循环将每个对象附加到数组,但是我需要每个问题都有正确的答案。

Questions类位于其他文件中:

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")
]

正如Aran-Fey指出的那样,您的语法不正确。

questions = [
    Questions(questionsPrompt[0], "a"),
    Questions(questionsPrompt[1], "b"),
    Questions(questionsPrompt[2], "a")
]

此外,还有一点,您要创建的是列表,而不是数组。 语义和实现方面都存在差异,并且由于Python两者都有,因此这是一个重要的区别。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM