第一种方法:
: M& N# j8 P0 p1 H( ^, }5 S: o# 定义一个学生类初始值为姓名,语文成绩,数学成绩,英语成绩
class Student:
def __init__(self, name, chinese, math, english):
self.name = name
self.chinese = chinese
self.math = math
self.english = english
self.allGrade = chinese + math + english
# 为了验证数值是否正确,加了个输出看一下
print(self.allGrade)
# 定义一个列表,用来装载所有成绩
result = []
while True:
# 录入信息
stuName = input("请输入姓名:")
stuChinese = float(input("请输入语文:"))
stuMath = float(input("请输入数学:"))
stuEnglish = float(input("请输入英语;"))
# 将每个人的信息实例化一个Student并存入列表。
result.append(Student(stuName, stuChinese, stuMath, stuEnglish))
# 判断是否继续添加
if input('是否继续添加(yes/no)') == 'no':
break
# 对结果进行排序
result = sorted(result, key=lambda a: a.allGrade, reverse=True)
# 输出结果
for i in result:
print(i.name) 第二种方法:+ s2 O1 ^+ P0 ]1 Z9 A: D: v# [- P' A
# 定义一个列表
result = []
while True:
# 录入信息
stuName = input("请输入姓名:")
stuChinese = float(input("请输入语文:"))
stuMath = float(input("请输入数学:"))
stuEnglish = float(input("请输入英语;"))
# 装到列表
result.append([stuName, stuChinese, stuMath, stuEnglish, stuChinese + stuMath + stuEnglish])
# 判断是否继续
if input('是否继续添加(yes/no)') == 'no':
break
# 排序
result = sorted(result, key=lambda a: a[4], reverse=True)
for i in result:
print(i) 然后顺便回顾一下冒泡排序算法:# 定义一个列表
result = []
while True:
# 录入信息
stuName = input("请输入姓名:")
stuChinese = float(input("请输入语文:"))
stuMath = float(input("请输入数学:"))
stuEnglish = float(input("请输入英语;"))
# 装到列表
result.append([stuName, stuChinese, stuMath, stuEnglish, stuChinese + stuMath + stuEnglish])
# 判断是否继续
if input('是否继续添加(yes/no)') == 'no':
break
# 冒泡排序
for i in range(len(result)):
for j in range(0, len(result) - i - 1):
if result[j][4] < result[j + 1][4]:
result[j], result[j + 1] = result[j + 1], result[j]
for i in result:
print(i)
- q4 R- O4 O% ^: L: P1 ]1 O5 s
* b0 ~$ A/ {! T. U/ @8 U4 Y4 ]# _ |