在新行上打印每个选项

时间:2017-10-06 06:43:43

标签: python python-2.7 python-3.x

这是我到目前为止的代码:

questions = ["What is 1 + 1","What is Batman's real name"]
answer_choices = ["1)1\n2)2\n3)3\n4)4\n5)5\n:","1)Peter Parker\n2)Tony Stark\n3)Bruce Wayne\n4)Thomas Wayne\n5)Clark Kent\n:"]
correct_choices = ["2","3",]
answers = ["1 + 1 is 2","Bruce Wayne is Batman"]

score = 0
answer_choices = [c.split()[:3] for c in answer_choices]
for question, choices, correct_choice, answer in zip(questions,answer_choices, correct_choices, answers):
    print(question)
    user_answer = str(input(choices))
    if user_answer in correct_choice:
        print("Correct")
        score += 1
    else:
        print("Incorrect", answer)
    print(score, "out of", len(questions), "that is", float(score /len(questions)) * 100, "%")

我的代码运行但是answer_choices(所以问题选项)不会显示在每个列表元素的新行上。我怎样才能做到这一点?解释也不错

3 个答案:

答案 0 :(得分:1)

你应该摆脱这一行,以便你的代码能够运作:

answer_choices = [c.split()[:3] for c in answer_choices

请注意,您不必拆分answer_choices,因为您不将每个问题的答案视为数组。

此外,您的代码中存在更多错误,例如最后的评分。这是代码的格式化和修复版本:

questions = [
"What is 1 + 1?",
"What is Batman's real name?"]

answer_choices = [
"1) 1\n2) 2\n3) 3\n4) 4\n5) 5\n\nYour answer: ",
"1) Peter Parker\n2) Tony Stark\n3) Bruce Wayne\n4) Thomas Wayne\n5) Clark Kent\n\nYour answer: "]

correct_choices = ["2","3",]

answers = [
"1 + 1 is 2",
"Bruce Wayne is Batman"]

score = 0

for question, choices, correct_choice, answer in zip(
questions,answer_choices, correct_choices, answers):
    print(question)
    user_answer = str(input(choices))
    if user_answer in correct_choice:
        print("Correct!\n")
        score += 1
    else:
        print("Incorrect! " + answer + "\n")

print score, "out of", len(questions), "that is", int(float(score)/len(questions)*100), "%"

答案 1 :(得分:0)

如果删除/注释该行

answer_choices = [c.split()[:3] for c in answer_choices]

你会得到你想要的输出。

由于answer_choices已经是一个String数组,因此在for循环中,您将访问answer_choices的每个数组元素。此外,由于answer_choices中的每个字符串都是您需要它们出现的格式,因此您无需拆分。

答案 2 :(得分:0)

删除

answer_choices = [c.split()[:3] for c in answer_choices]

它给出了您的预期输出