背景:310名学生分组汇报,每组最多8人。已经自由组队了34组(有的不足8人)。
已知:全部名单、自由组队名单
问题:将剩余学生进行分组
输出:分组名单、dict{学生:组号}便于登记分数
分析:关键--找出未分组的学生。
显然是一个集合运算,但未找到excel相关功能,因此考虑脚本代码实现
- 创建二维列表
li = [[] for i in range(40+1)]
- python excel读、写的操作对象是分开独立的
- str判断中文字符
import xlrd
xls = xlrd.open_workbook('21自辨.xls')
sheets = xls.sheets() # [0]打开第一张表
"""
traverse read sheet[1]
output: dict[str: int] + 已有组数int
"""
def filter_name(name):
if not (u'\u4e00' <=name[-1] <= u'\u9fff'):
name=name[:-1]
return name
def name_to_group_ind(table):
name_dict={}
nrows = table.nrows # 行数
for i in range(1, nrows):
for cell in table.row_values(i)[1:]:
if cell:
name=filter_name(cell[:3])
if name in name_dict.keys():
print(f"{i}组{cell}增加失败:与{name_dict[name]}组{name}重复!")
else:
name_dict[name]=i
print(f"{len(name_dict)}人已完成,{nrows-1}组已分组,余{(nrows-1)*8-len(name_dict)}空位")
return name_dict, nrows
name_dict, nrows = name_to_group_ind(sheets[1])
"""
traverse write sheet[0]
"""
from xlutils.copy import copy
# xlsnew.save('21自辨-t.xls')
def write_while_group_continue(table, base, name_dict, xls_wt): # rd\wt是两个对象
groups=[[] for i in range(40+1)]
table_wt = xls_wt.get_sheet(0)
cnt=0
table_wt.write(0,4,"分组")
for r in range(1, table.nrows):
name=table.row_values(r)[2][:3]
if name in name_dict.keys():
# print(f"{name}:{name_dict.get(name)}")
g_id=name_dict.get(name)
table_wt.write(r,4,g_id)
groups[g_id].append(name)
else:
g_id=cnt//8+base
cnt+=1
# print(f"{name}:未分组{g_id}-{cnt}")
table_wt.write(r, 4, g_id)
groups[g_id].append(name)
assert len(name_dict)+cnt== table.nrows-1
print(f"{cnt}人再分组,新增{cnt//8}组")
#####
table2_wt = xls_wt.get_sheet(1)
for r in range(base, len(groups)):
for i in range(len(groups[r])):
print(r,i+1,groups[r][i])
table2_wt.write(r,i+1,groups[r][i])
xls_wt.save('21自辨分组.xls')
return groups
groups=write_while_group_continue(sheets[0], nrows, name_dict, copy(xls))