我试图制作一个随机组生成器,将学生列表分成几乎相等的分区(例如,如果有11个学生和3个组,我们需要两组四个和一个组3)。我们需要为x次分配重复此过程。我们从文件中读取学生列表,并从文件中读取组。这是我到目前为止的代码:
import csv
import unittest
def studentgenerator(num_asmt, num_stud, student_list,
assignment_teams):
with open(student_list , "r") as student:
list_students = csv.reader(student)
student_groups = []
for x in range (0, num_asmt):
random.shuffle(list_students)
div = len(list_students)/float(num_stud)
for x in xrange(num_stud):
student_groups = lst[int(round(div * x)): int(round(div *
(x + 1))]\
for group in student_groups:
with open(assignment_teams, "w") as team:
list_assignment_groups = csv.writer(team)
list_assignment_groups.writerow(group)
student_list.close()
assignment-teams.close()
我似乎无法让分区程序以我想要的方式运行,而且我认为从文件读取/输出出现问题,但我不确定正是我做错了什么。
答案 0 :(得分:1)
您可以定义一个chunker来为您进行拆分。事实上,这是一个真正的“发电机”。由@Ned Batchelder提供(在那里)。
import random
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
n = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']
random.shuffle(n)
list(chunks(n, 3))
# [['B', 'H', 'G'], ['D', 'A', 'C'], ['E', 'F', 'I'], ['J', 'K']]
答案 1 :(得分:0)
import random
while True:
n = int(input("Enter the class strength"))
students = [[i] for i in range(1,n+1)]
x = len(students)
tNum = 0
#Nmber of teams
print('The possible number of teams are')
for i in range(1, x + 1):
if x % i == 0:
print(i)
y = int(input("Enter the no of teams"))
if n == 0 or y == 0:
print("Enter valid entries please")
continue
z = int(x/y)
#Loop
while x > 0:
if x%z == 0:
print("Team",tNum + 1)
tNum +=1
choice = random.choice(students)
students.remove(choice)
x = len(students)
print(choice)
q = input("Do you want to close or continue ? [y/n]")
if q == "y":
continue
else:
break