QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

泡泡马甲APP 更多内容请下载泡泡马甲手机客户端APP 立即下载 ×
查看: 2657|回复: 0

[Python] 循环输入学生和成绩,最后按照总成绩进行排序

[复制链接]

等级头衔

积分成就    金币 : 2806
   泡泡 : 1516
   精华 : 6
   在线时间 : 1244 小时
   最后登录 : 2024-5-5

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老

联系方式
发表于 2020-7-26 19:38:08 | 显示全部楼层 |阅读模式
第一种方法:
+ T& M( b' O" F
  1. # 定义一个学生类初始值为姓名,语文成绩,数学成绩,英语成绩
  2. class Student:
  3.     def __init__(self, name, chinese, math, english):
  4.         self.name = name
  5.         self.chinese = chinese
  6.         self.math = math
  7.         self.english = english
  8.         self.allGrade = chinese + math + english
  9.         # 为了验证数值是否正确,加了个输出看一下
  10.         print(self.allGrade)
  11. # 定义一个列表,用来装载所有成绩
  12. result = []
  13. while True:
  14.     # 录入信息
  15.     stuName = input("请输入姓名:")
  16.     stuChinese = float(input("请输入语文:"))
  17.     stuMath = float(input("请输入数学:"))
  18.     stuEnglish = float(input("请输入英语;"))
  19.     # 将每个人的信息实例化一个Student并存入列表。
  20.     result.append(Student(stuName, stuChinese, stuMath, stuEnglish))
  21.     # 判断是否继续添加
  22.     if input('是否继续添加(yes/no)') == 'no':
  23.         break
  24. # 对结果进行排序
  25. result = sorted(result, key=lambda a: a.allGrade, reverse=True)
  26. # 输出结果
  27. for i in result:
  28.     print(i.name)
第二种方法:; _/ L5 V8 Z9 Y9 C0 l& v
  1. # 定义一个列表
  2. result = []
  3. while True:
  4.     # 录入信息
  5.     stuName = input("请输入姓名:")
  6.     stuChinese = float(input("请输入语文:"))
  7.     stuMath = float(input("请输入数学:"))
  8.     stuEnglish = float(input("请输入英语;"))
  9.     # 装到列表
  10.     result.append([stuName, stuChinese, stuMath, stuEnglish, stuChinese + stuMath + stuEnglish])
  11.     # 判断是否继续
  12.     if input('是否继续添加(yes/no)') == 'no':
  13.         break
  14. # 排序
  15. result = sorted(result, key=lambda a: a[4], reverse=True)
  16. for i in result:
  17.     print(i)
然后顺便回顾一下冒泡排序算法:
  1. # 定义一个列表
  2. result = []
  3. while True:
  4.     # 录入信息
  5.     stuName = input("请输入姓名:")
  6.     stuChinese = float(input("请输入语文:"))
  7.     stuMath = float(input("请输入数学:"))
  8.     stuEnglish = float(input("请输入英语;"))
  9.     # 装到列表
  10.     result.append([stuName, stuChinese, stuMath, stuEnglish, stuChinese + stuMath + stuEnglish])
  11.     # 判断是否继续
  12.     if input('是否继续添加(yes/no)') == 'no':
  13.         break
  14. # 冒泡排序
  15. for i in range(len(result)):
  16.     for j in range(0, len(result) - i - 1):
  17.         if result[j][4] < result[j + 1][4]:
  18.             result[j], result[j + 1] = result[j + 1], result[j]
  19. for i in result:
  20.     print(i)
" h0 E# n! j( L- e5 M3 d

2 G" b) s& f2 R& y, r" K
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号 )

GMT+8, 2024-5-14 03:27

Powered by paopaomj X3.4 © 2016-2024 sitemap

快速回复 返回顶部 返回列表