Skip to main content
 首页 » 编程设计

python之重复随机选择中不重复元素

2024年09月07日10mq0036

我有两个文本文件,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. 

备注:

这比 the solution by Jojo 慢得多使用 random.sample(..) 因为您需要重新排列每个学生的完整问题列表,而 random.sample() 只会为每个学生抽取 k 个样本。

随机数独:https://docs.python.org/3/library/random.html#random.shuffle