不重复随机选择中的元素

时间:2018-01-10 12:31:12

标签: python python-3.x

我有两个文本文件studentsquestions。在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()

3 个答案:

答案 0 :(得分:1)

你想要的是绘制random sample个问题。来自文档:

  

random.sample(population,k):返回从总体序列中选择的k个长度的唯一元素列表。用于无需替换的随机抽样。

通过这种方式,您可以避免为单个学生多次绘制相同的问题。

类似的东西:

for studens in splitedstud:
    file = open(studens + ".txt", "w")
    random_questions = random.sample(splited, k)
    for rand_question in random_questions:
         file.write(rand_question + '\n')
    file.close()

答案 1 :(得分:1)

如果您想使用一个问题配对每个学生:

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.

备注:

这比使用random.sample(..)的{​​{3}}要慢得多,因为你需要为每个学生重新调整问卷的清单,而random.sample()每个学生只会抽取k个样本。

Doku for shuffle:the solution by Jojo

答案 2 :(得分:0)

更改

splited = questions1.read().split('\n')

splited = list(set(questions1.read().split('\n')))

删除所有重复的问题。