繁体   English   中英

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

[英]Python 3 - Having 2 items as 1 index in a list

在此处输入图片说明

我是 python 新手,我正在尝试构建一个测验。 所以其中一个问题包含 2 个答案,但我不知道如何接受这两个答案。 如图所示,我希望“这个”和“那个”都可以作为答案。 有没有办法做到这一点? 提前致谢!

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()

你应该改变你的数据结构。 而不是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

或者将您的“答案”作为字典。

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

字典操作链接

暂无
暂无

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

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