我的課程是關於一款遊戲。到目前爲止,我已經編制了註冊程序,但是它的第二項任務是它按照隨機順序爲測驗產生問題。如何隨機化python測驗中的問題順序?
我已經設法提出問題和答案,但是,我不知道如何在每次新用戶播放時使它們以不同的順序出現。我試過使用random.randint()
代碼,但我認爲我沒有正確使用它。
我的課程是關於一款遊戲。到目前爲止,我已經編制了註冊程序,但是它的第二項任務是它按照隨機順序爲測驗產生問題。如何隨機化python測驗中的問題順序?
我已經設法提出問題和答案,但是,我不知道如何在每次新用戶播放時使它們以不同的順序出現。我試過使用random.randint()
代碼,但我認爲我沒有正確使用它。
那麼,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,2或3。這是否意味着我把所有的問題放在一邊? –
這個答案是一個非常詳細的說「使用random.shuffle」的方法。 –
是的,它是@ ron.rothman –
隨機模塊中有choice
函數。 如果問題是隨機選擇問題,則可以簡單地使用它。
import random
questions = ['Question1', 'Question2', 'Question3']
random.choice(questions)
要小心,如果questions
是空的,random.choice
提高IndexError
你檢查'random.shuffle'? –
您應該可能顯示您現有的解決方案。 –