# 需求,输入不少于0个学生,将分数从高到低排序出来
class Student:
def __init__(self, student_name, student_score):
self.student_name = student_name
self.student_score = student_score
class StudentList:
def __init__(self):
self.student_list = list()
self.set_students()
self.get_students()
self.desc_sort()
self.get_students()
def set_students(self):
print('每行输入一个学生姓名和分数空,输入end结束....')
while True:
get_string = input('请输入姓名和分数之间空格隔开:')
if get_string == 'end':
break
name, score = get_string.split()
self.student_list.append(Student(name, float(score)))
# 交换两个数值,声明为静态方法
@staticmethod
def swap_num(num1, num2):
return num1 , num2
# 倒叙排序方法 选择排序
def desc_sort(self):
if len(self.student_list) == 0:
raise Exception('序列为空!')
student_len = len(self.student_list)
for i in range(student_len - 1):
print('正在比较第{}个学生的分数'.format(i))
max_index = i # 假设最大的是当前这个
j = i + 1
while j < student_len:
if self.student_list[j].student_score > self.student_list[max_index].student_score:
max_index = j
j += 1
if max_index != i:
self.student_list[i], self.student_list[max_index] = \
self.swap_num(self.student_list[max_index], self.student_list[i])
def get_students(self):
for student in self.student_list:
print(student.student_name, student.student_score)
if __name__ == '__main__':
StudentList()
网友评论