编程:输入一组学生信息,包括姓名、年龄,请分别按照姓名、年龄排序并输出。
时间: 2024-03-24 07:40:23 浏览: 32
好的,这是一个简单的排序问题,你可以使用任何一种排序算法来解决它。以下是一种基于Python的解决方案:
```python
# 定义一个学生类
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"{self.name} {self.age}"
# 输入学生信息
students = []
while True:
name = input("请输入学生姓名:")
if not name:
break
age = int(input("请输入学生年龄:"))
student = Student(name, age)
students.append(student)
# 按姓名排序并输出
students_by_name = sorted(students, key=lambda student: student.name)
print("按姓名排序:")
print(students_by_name)
# 按年龄排序并输出
students_by_age = sorted(students, key=lambda student: student.age)
print("按年龄排序:")
print(students_by_age)
```
运行以上代码并按照提示输入学生信息,程序会按照姓名和年龄分别排序并输出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)