QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

手机号码,快捷登录

查看: 3127|回复: 0

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

[复制链接]

等级头衔

积分成就    金币 : 2857
   泡泡 : 1516
   精华 : 6
   在线时间 : 1316 小时
   最后登录 : 2025-2-20

丰功伟绩

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

联系方式
发表于 2020-7-26 19:38:08 | 显示全部楼层 |阅读模式
第一种方法:
: 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 ]# _
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2025-2-22 17:00

Powered by paopaomj X3.5 © 2016-2025 sitemap

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