在某Python交流群看到了这样一个问题
然后到晚上9点似乎他还没有搞定,于是掏出了我的pycharm。
一种是结构体(以前在C#里面是这么叫的),其实就是class,定义一个学生类,然后就是学生姓名,成绩,总成绩
然后用sort排序(还有些手动排序方法快要忘了。),一种就是直接列表。
第一种方法:
# -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author :Lan @ blog :www.lanol.cn @ Date : 2020/7/24 @ Description:I'm in charge of my Code ------------------------------------------------- """ # 定义一个学生类初始值为姓名,语文成绩,数学成绩,英语成绩 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)
第二种方法:
# -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author :Lan @ Blog :www.lanol.cn @ Date : 2020/7/24 @ Description:I'm in charge of my Code ------------------------------------------------- """ # 定义一个列表 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)
然后顺便回顾一下冒泡排序算法:
# -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author :Lan @ Blog :www.lanol.cn @ Date : 2020/7/24 @ Description:I'm in charge of my Code ------------------------------------------------- """ # 定义一个列表 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)
发表评论