学校选拔篮球队员,每间宿舍最多有 4 个人。现给出宿舍列表,请找出每个宿舍最高的同学。定义一个学生类 Student,有身高 height,体重 weight 等。
时间: 2024-06-12 13:06:34 浏览: 73
让每一个人都有机会—朗讯科技的人力资源管理.zip___让每一个人都有机会—朗讯科技的人力资源管理.zip
可以使用字典来存储每个宿舍的学生信息,然后遍历字典找出每个宿舍最高的同学。
示例代码如下:
```python
class Student:
def __init__(self, height, weight):
self.height = height
self.weight = weight
student_list = [
Student(170, 60),
Student(175, 65),
Student(180, 70),
Student(165, 55),
Student(172, 62),
Student(185, 75),
Student(168, 58),
Student(178, 68),
]
dormitory_dict = {
"A": [],
"B": [],
"C": [],
"D": [],
}
# 将学生随机分配到宿舍
import random
for student in student_list:
dormitory = random.choice(["A", "B", "C", "D"])
if len(dormitory_dict[dormitory]) < 4:
dormitory_dict[dormitory].append(student)
# 找出每个宿舍最高的同学
for dormitory, students in dormitory_dict.items():
if len(students) > 0:
tallest_student = max(students, key=lambda s: s.height)
print(f"The tallest student in dormitory {dormitory} is {tallest_student.height}cm tall.")
else:
print(f"There is no student in dormitory {dormitory}.")
```
输出结果类似于:
```
The tallest student in dormitory A is 170cm tall.
The tallest student in dormitory B is 178cm tall.
The tallest student in dormitory C is 180cm tall.
The tallest student in dormitory D is 185cm tall.
```
阅读全文