2015-06-21 56 views
-3

我的课程是关于一款游戏。到目前为止,我已经编制了注册程序,但是它的第二项任务是它按照随机顺序为测验产生问题。如何随机化python测验中的问题顺序?

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

+1

你检查'random.shuffle'? –

+4

您应该可能显示您现有的解决方案。 –

回答

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核对答案。你如何做到这一点是你的选择。这应该是帮助你的基础。

+0

哦,非常感谢,但是,我还在每个问题下键入了答案选择的东西,因此用户会选择选项1,2或3。这是否意味着我把所有的问题放在一边? –

+0

这个答案是一个非常详细的说“使用random.shuffle”的方法。 –

+0

是的,它是@ ron.rothman –

0

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

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

要小心,如果questions是空的,random.choice提高IndexError