我有两个文本文件,students
和questions
。在students
是学生,在questions
是问题。每个学生对应一个问题,但有时问题是相同的,我不想重复问题。
import random
k = int(input("how many questions do you want ? -"))
questions1 = open("question.txt",'r')
studenti = open("students.txt",'r')
splited = questions1.read().split('\n')
splitedstud = student1.read().split('\n')
for studens in splitedstud:
file = open(studens + ".txt", "w")
for i in range(int(k)):
questiion = random.choice(splited)
file.write(questiion + '\n')
file1 = open(studens + ".txt", "r")
f = file1.read()
if questiion in f:
continue
file.close()
questions.close()
students.close()
如果要将每个学生与一个问题恰好配对,请使用:
import random
studs = [chr(ord('a')+x) for x in range(20)] # testdata - instead of your read in files
ques = ["question"+str(x) for x in range(20)] # the files in, just demodata
random.shuffle(ques) # get questions into a random arrangement
for p in zip(studs,ques): # pairs each student to the same indexed question [(s1,q1),...]
with open(p[0]+".txt","w") as f: # with syntax: better than using blank open/close ops
f.write(p[1])
输出:
20 files 'a.txt' to 'p.txt' containing one random question from ques - no duplicates over all files.
如果输入中的任何一个列表zip()
较短,则zip只会创建该项目的配对,其余的将被丢弃-因此请确保您至少有len(studenti)
疑问。
对于每个学生一个以上的问题,无需重复,您可以使用:
for s in studs:
# randomize questions for each student
random.shuffle(ques)
amount = random.randint(3,8) # how many to be put into file
with open(s+".txt","w") as f:
for n in (range(amount)): # write questions into file
f.write(ques[n] + "\n")
输出:
20 files 'a.txt' to 'p.txt' containing random 3-8 question from ques - no duplicates inside each file.
备注:
这比Jojo使用的解决方案要慢得多,random.sample(..)
因为您需要重新整理每个学生的完整问题清单,而每个学生random.sample()
只能抽取k个样本。
Doku随机播放:https ://docs.python.org/3/library/random.html#random.shuffle
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句