Python 3-在列表中将2个项目作为1个索引

时间:2018-12-05 16:21:18

标签: python python-3.x

enter image description here

我是python的新手,我正在尝试构建一个测验物。 因此,其中一个问题包含2个答案,但我无法弄清楚如何接受这两个答案。如图所示,我想同时拥有“ this”和“ that”作为答案。有办法吗? 预先感谢!

questions_asked = [
    "Q1",
    "Q2",
]

answers = [
    "Answer",
    "This" or "That"
]


def run_question():
    score = 0
    index = 0
    for question in questions_asked:
        if index < len(questions_asked):
            answer = input(questions_asked[index]).lower()

            if answer == answers[index].lower():
                score += 1
        index += 1
    print("{score} out of 2".format(score=score))


run_question()

2 个答案:

答案 0 :(得分:3)

您应该更改数据结构。您应该使用answers: List[str]

而不是answers: List[set]
answers = [{"one answer"}, {"another answer"}, {"a couple", "correct answers"}]

然后您可以使用以下方法进行检查:

expected = answers[i]  # however you're doing this -- I'd probably zip it together
                       # with questions, but YMMV
if user_answer in expected:
    # correct

请注意,您的循环可以大大简化:

score = 0
for question, expected_answers in zip(questions_asked, answers):
    user_answer = input(question).lower()
    if user_answer in expected_answers:
        score += 1

答案 1 :(得分:0)

或将“答案”作为字典。

dict = {'answer1': 'this', 'answer2': 'that', 'answer3': 'None'}

link for dictionary manipulation