如何在Python中实现列表分组并输出?编写f3Groups()分组函数
实现学生分组与指定格式输出
需求概述
编写f3Groups()函数,接收学生列表参数,返回包含3个小组子列表的cgList:
- 无学生时返回空列表
- 存在学生时,3个小组子列表均不能为空
- 分组规则:第1、4、7…位学生归Group1;第2、5、8…位归Group2;第3、6、9…位归Group3
- 按指定格式输出全班列表及各组列表
完整代码实现
def get_student_list(): stdlist = [] while True: iStr = input('Please enter a new student name, ("quit" if no more student)') if iStr == "quit": return stdlist if iStr == "": print("Empty student name is not allowed.") else: stdlist.append(iStr) def f3Groups(student_list): if not student_list: return [] group1, group2, group3 = [], [], [] # 按索引模3结果分配小组 for idx, name in enumerate(student_list): if idx % 3 == 0: group1.append(name) elif idx % 3 == 1: group2.append(name) else: group3.append(name) return [group1, group2, group3] # 获取学生列表 stdList = get_student_list() # 输出全班列表 print(f"The whole class list is {stdList}") # 输出分组结果 if stdList: groups = f3Groups(stdList) print(f"Group 1: {groups[0]}") print(f"Group 2: {groups[1]}") print(f"Group 3: {groups[2]}")
关键说明
- 分组逻辑:利用
enumerate()获取学生的索引(从0开始),通过索引对3取余的结果判断归属小组,完美匹配第1/4/7、2/5、3/6位的分组要求。 - 格式输出:使用f-string直接格式化列表输出,与示例格式完全一致。
- 边界处理:无学生时
f3Groups()返回空列表,此时仅输出全班空列表,不输出分组信息。
测试效果
输入7个学生Student a至Student g后,输出如下:
The whole class list is ['Student a', 'Student b', 'Student c', 'Student d', 'Student e', 'Student f', 'Student g'] Group 1: ['Student a', 'Student d', 'Student g'] Group 2: ['Student b', 'Student e'] Group 3: ['Student c', 'Student f']
内容的提问来源于stack exchange,提问作者noobatprogramming
相关产品推荐
相关产品推荐

