我正在使用Python,并希望改进这些由我自己编写的有关随机分组的代码。我希望有一种有效的编码样式来随机生成分组,每个团队有5名学生,并且需要从10个总体中随机分配一个案例
我尝试使用2个循环和字典将键作为大小写添加,并将值作为学生添加,并尝试找出将5个学生分组的格式,并在while循环部分显示他们的情况
#sample data
students_list =['s1','s2','s3','s4','s5','s6','s7','s8','s9','s10']
cases_list =['case1','case2','case3','case4','case5','case6','case7','case8','case9','case10']
import random
match_dict = {}
count = 0
random.shuffle(cases_list)
if len(students_list) <= len(cases_list) and len(students_list) > 0:
for case in cases_list:
for student in students_list:
if case not in match_dict.keys():
match_dict[case] = student
students_list.remove(student)
else:
raise ValueError("Not enough case!")
print("\n")
my_case = list(match_dict.keys())
my_student = list(match_dict.values())
cases = []
group = int(len(my_student)/5)
while count < len(my_student):
for num in range(0,group):
print("Group {my_group}".format(my_group = num +1))
for i in range(count,count+5):
print("Studnet ID: ",my_student[i+0])
cases.append(my_case[i+0])
print("Assigned cases are ",cases)
count = count + 5
cases = []
print("\n -----Next group----- \n")
预期结果
Group 1
Studnet ID: s1
Studnet ID: s4
Studnet ID: s7
Studnet ID: s8
Studnet ID: s10
Assigned cases are n
-----下一组-----
答案 0 :(得分:0)
import random
students_list = [
's1','s2','s3','s4','s5',
's6','s7','s8','s9','s10'
]
cases_list = [
'case1','case2','case3','case4','case5',
'case6','case7','case8','case9','case10'
]
random.shuffle(students_list)
random.shuffle(cases_list)
groups = [students_list[i:i + 5] for i in range(0, len(students_list), 5)]
for i, g in enumerate(groups):
print("Group", i + 1)
for s in g:
print("Student ID", s)
print("Cases: ", end = "")
for j in range(i * 5, (i * 5) + 5):
print(cases_list[j], end = ", ")
print("\n- - - - -")
我不完全了解您的要求,这与您的期望相比如何?