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

2024-10-01 15:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个档案:档案(学生)里有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()

Tags: txtclosereadrandom档案open学生file
1条回答
网友
1楼 · 发布于 2024-10-01 15:29:06

下面是一些你可以使用的代码。希望能给你一些想法。你知道吗

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

相关问题 更多 >

    热门问题