如何在python中的测验中随机化问题的顺序?

时间:2015-06-21 22:46:35

标签: python

我的课程是关于游戏的。到目前为止,我已对程序进行了编程,但在第二项任务中,它表示以随机顺序为测验生成问题。

我设法提出问题和答案但是,我不知道每次新用户播放时如何使它们以不同的顺序出现。我尝试使用random.randint()代码,但我认为我没有正确使用它。

2 个答案:

答案 0 :(得分:1)

好吧,random.randint()返回一个带有随机数整数的列表。你真正需要的是random.shuffle()。所以你应该制作一个列表(我称之为questions)因为random.shuffle仅在括号中有列表时才有效。这应该有效,因为您需要做的只是将您的问题放在列表中,让random.shuffle()发挥其魔力:

questions = ['Question 1', 'Question 2', 'Question 3'] #You can add as many questions as you like
random.shuffle(questions)  #Mixes the items in "questions" into a random order
print questions[0]
print questions[1]
print questions[2]

您可以通过这种方式使用random.shuffle()获得许多不同的组合/结果。除了你需要一个while循环并知道问题的顺序以便你可以为每个问题选择正确的答案选择之外,还要有相同的答案。仍在为答案添加random.shuffle()

questions = ['Question 1', 'Question 2', 'Question 3']
originals = [['Question 1', 'a1'], ['Question 2', 'b1'], ['Question 3', 'c1']]
answers = [['a1'], ['a2'], ['a3']], [['b1'], ['b2'], ['b3']], [['c1'], ['c2'], ['c3']]        #List of answers for each question
selected_answers = [] #Contains selected answers
random.shuffle(questions)
random.shuffle(answers[0])
random.shuffle(answers[1])
random.shuffle(answers[2])
question = 0
while question < 4:
    if questions[0] == 'Question 1':
        print 'Question 1'
        print answers[0][0], answers[0][1], answers[0][2]
        chosen = raw_input('Enter 1 for the first answer, 2 for the second answer and 3 for the third one.')
        selected_answers.append(chosen)
        del questions[0]
        question += 1
    elif questions[0] == 'Question 2':
        print 'Question 2'
        print answers[1][0], answers[1][1], answers[1][2]
        chosen = raw_input('Enter 1 for the first answer, 2 for the second answer and 3 for the third one.')
        selected_answers.append(chosen)
        del questions[0]
        question += 1
    elif questions[0] == 'Question 3':
        print 'Question 3'
        print answers[2][0], answers[2][1], answers[2][2]
        chosen = raw_input('Enter 1 for the first answer, 2 for the second answer and 3 for the third one.')
        selected_answers.append(chosen)
        del questions[0]
        question += 1

使用originals,您可以使用正确的问题检查selected_answers的答案。你如何做到这一点是你的选择。这应该是一个帮助你的基础。

答案 1 :(得分:0)

随机模块中有choice个函数。 如果问题是随机选择问题,你可以简单地使用它。

import random
questions = ['Question1', 'Question2', 'Question3']
random.choice(questions)

请注意,如果questions为空,random.choice会引发IndexError