以下面的题为例子:
班上有35个学生,要对他们进行关于28个中国省会城市的小测验,现在打算打乱问题次序,让每一份试卷独一无二。
#create 30 quizs with questions and answers in random,along with the answers keyself.
import random
#the quiz data . keys are the province and values are the procincial capital.
capitals = {'河北省':'石家庄','山西省':'太原','辽宁省':'沈阳','吉林省':'长春',
'黑龙江省':'哈尔滨','江苏省':'南京','浙江省':'杭州','安徽省':'合肥','福建省':'福州',
'山东省':'济南','河南省':'郑州','广东省':'广州','湖南省':'长沙','湖北省':'武汉',
'海南省':'海口','四川省':'成都','贵州省':'贵阳','云南省':'昆明','陕西省':'西安',
'甘肃省':'兰州','青海省':'西宁','台湾省':'台北','内蒙古自治区':'呼和浩特',
'广西壮族自治区':'南宁','西藏自治区':'拉萨','宁夏回族自治区':'银川',
'新疆维吾尔自治区':'乌鲁木齐','江西省':'南昌'}
#需求 :创建35份试卷,和35份答案,每一份试卷上的题目随机排列
#create 35 quizs
for quizNum in range (35):
#create the quizes and answers keys files
quizfile = open('ProvinceQuiz%s.txt' % (quizNum + 1),'w')
answerfile = open('ProvinceAnswer%s.txt' % (quizNum + 1),'w')
#write out the header for the quizes
quizfile.write('Name:\nClass:\nNumber:\n')
quizfile.write((' '*20) + 'this is ProvinceQuiz%s'%(quizNum +1))
quizfile.write('\n\n')
#shuffle the order of the province
province = list(capitals.keys())
random.shuffle(province)
#loop through all 28 province, make a question for each
for questionNum in range (28):
#get right and wrong answers
rightanswer = capitals[province[questionNum]]
wronganswer = list(capitals.values())
del wronganswer[wronganswer.index(rightanswer)]
answeroptions = random.sample(wronganswer,3)
answeroptions = [rightanswer] + answeroptions
random.shuffle(answeroptions)
#write the question and answer options to the quiz files
quizfile.write('%s.What is the capital of %s ?\n'%(questionNum +1 , province[questionNum]))
for i in range(4):
quizfile.write(' %s.%s\n'%('ABCD'[i],answeroptions[i]))
#write the answer keys to answer key files
answerfile.write(' %s.%s\n'%(questionNum + 1,'ABCD'[answeroptions.index(rightanswer)]))
quizfile.close()
answerfile.close()