如何在文本文件中随机配对数据

时间:2018-03-25 11:38:41

标签: python python-3.x

我有两个文件:有20名学生的文件(学生)和有3名讲师的文件(讲师)。我想随机配对学生和讲师。例如:
讲师(1)=学生(2),学生(3),学生(19)
讲师(3)=学生(20),学生(23)......

这是我试过的代码。它的表现并不像我希望的那样:

import  random
lecturer = open("lecturer.txt", "r")
students = open("students.txt", "r")
spliti = lecturer.read().split("\n")
splitis = students.read().split("\n")
stud = (random.choice(splitis))


for stud in splitis:
   file = open(stud + "txt","w")
    for i in range():
     questinss = random.choice(spliti)
    file.write(lecturer + "\n")
    files = open(students + ",txt", "r")
    file.close()
    lecturer.close()
    students.close()

1 个答案:

答案 0 :(得分:0)

以下是您可以使用的一些代码。希望它可以给你一些想法。

import random

# get the students
with open('student.txt','r') as f:
    students = f.read().split()

# get the lectures
with open('lecture.txt','r') as f:
    lectures = f.read().spilt()

# since you only have three different lectures, we can sequently
# collect them as 0,1,2

reflist = []
for student in students:
    reflist.append( lectures[ random.randrange(3) ] )



# prepare for the print
lecture_student = []
for lecture in lectures:
    count = 0
    ls = []
    for ndx in reflist:
        if lecture == ndx:
            ls.append(students[count])
        count += 1

    lecture_student.append(ls)


# now to file them
with open('pro_lecture_student.txt','wt') as f:
    count = 0
    for lecture in lectures:
        f.write(lecture)
        f.write(': ')
        for student in lecture_student[count]:
            f.write(student)
        f.write('\n\n')
        count += 1