请用python编写一个函数,使用字典存储学生信息,学生信息包括学号和姓名,并分别根据学生学 号升序、学生姓名首字母升序输出学生的信息。
时间: 2023-05-21 21:04:41 浏览: 160
Certainly, here is an example Python function that uses dictionaries to store student information, and outputs it in ascending order by student ID and by name initial:
```python
def print_student_info(students):
# sort students by ID in ascending order
sorted_by_id = sorted(students.items(), key=lambda kv: kv[0])
# sort students by name initial in ascending order
sorted_by_name = sorted(students.items(), key=lambda kv: kv[1])
print("Students sorted by ID:")
for id, name in sorted_by_id:
print("ID: {}, Name: {}".format(id, name))
print("\nStudents sorted by name initial:")
for id, name in sorted_by_name:
print("ID: {}, Name: {}".format(id, name))
# example usage
students = {123: "John Smith", 456: "Jane Doe", 789: "Bob Johnson"}
print_student_info(students)
```
Note that this function takes a dictionary `students` as input, which maps student IDs to names. The `sorted()` function is used with lambda functions as keys to sort the dictionary items based on either the ID or the name initial. The resulting sorted lists are then printed in the desired format.
I hope that helps with your question!
阅读全文