以下是一个示例代码,展示了如何按条件分组:
# 假设有一个包含学生姓名和成绩的字典列表
students = [
{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 76},
{'name': 'Charlie', 'score': 92},
{'name': 'David', 'score': 80},
{'name': 'Eve', 'score': 92},
{'name': 'Frank', 'score': 76}
]
# 创建一个空字典,用于存储分组结果
grouped_students = {}
# 遍历学生列表
for student in students:
score = student['score']
# 检查分数是否已经作为键存在于字典中
if score in grouped_students:
# 如果存在,将当前学生添加到该键对应的列表中
grouped_students[score].append(student)
else:
# 如果不存在,创建一个新的键,并将当前学生添加到列表中
grouped_students[score] = [student]
# 打印分组结果
for score, students in grouped_students.items():
print(f"学生成绩为 {score} 的学生有:")
for student in students:
print(student['name'])
print()
这段代码将根据学生的成绩将学生进行分组,并打印出每个分组中的学生姓名。结果如下:
学生成绩为 85 的学生有:
Alice
学生成绩为 76 的学生有:
Bob
Frank
学生成绩为 92 的学生有:
Charlie
Eve
学生成绩为 80 的学生有:
David
你可以根据实际需求修改代码,进行不同的条件分组。
下一篇:按条件分组 - Pandas