#=============================
#6.6 文件系统(File System)
#=============================#+++++++++++++++++++++++++++++
#6.6.3 Python中的文件操作
#+++++++++++++++++++++++++++++#<程序:读取文件os.py>
f = open("./Task1.txt",'r'); fls = f.readlines()
for line in fls:line = line.strip(); print (line)
f.close()#<程序:读取文件os.py,计算并写回>
f = open("./Task1.txt",'r+'); fls = f.readlines()
for line in fls:line = line.strip(); lstr = line.split()if lstr[0] == '3':res = 0for e in lstr[1:]:res+=int(e)
f.write('\n4 '+str(res)); f.close()#+++++++++++++++++++++++++++++
#6.6.4 学生实例4.6.3扩展
#+++++++++++++++++++++++++++++#<程序:存储考试结果到class1.txt文件>
class student:def __init__ (self,mname,studentID):self.name = mname; self.StuID = studentID;  self.Course_Grade = {};self.Course_ID = []; self.GPA = 0;    self.Credit = 0def selectCourse(self,CourseName,CourseID):self.Course_Grade[CourseID]=0;          #CourseID:0 加入字典self.Course_ID.append(CourseID)         # CourseID 加入列表self.Credit = self.Credit+ CourseDict[CourseID].Credit #总学分数更新def getInfo(self):print("Name:",self.name);print("StudentID",self.StuID);print("Course:")for courseID,grade in self.Course_Grade.items():print(CourseDict[courseID].courseName,grade)print("GPA",self.GPA);  print("Credit",self.Credit); print("")def TakeExam(self, CourseID):self.Course_Grade[CourseID]=random.randint(50,100)self.calculateGPA()def Grade2GPA(self,grade):if(grade>=90):return 4elif(grade>=80):return 3elif(grade>=70):return 2elif(grade>=60):return 1else:return 0def calculateGPA(self):g = 0;#遍历每一门所修的课程for courseID,grade in self.Course_Grade.items():g = g + self.Grade2GPA(grade)* CourseDict[courseID].Creditself.GPA = round(g/self.Credit,2)class Course:def __init__ (self,cid,mname,CourseCredit,FinalDate):self.courseID = cidself.courseName = mnameself.studentID = []self.Credit = CourseCreditself.ExamDate = FinalDatedef SelectThisCourse(self,stuID):   #记录谁修了这门课,在studentID列表里self.studentID.append(stuID)def setupCourse (CourseDict): #建立CourseList: list of Course objectsCourseDict[1]=Course(1,"Introducation to Computer Science",4,1)CourseDict[2]=Course(2,"Advanced Mathematics",5,2)CourseDict[3]=Course(3,"Python",3,3)CourseDict[4]=Course(4,"College English",4,4)CourseDict[5]=Course(5,"Linear Algebra",3,5)def setupClass (StudentDict):    #输入一个空列表NameList = ["Aaron","Abraham","Andy","Benson","Bill","Brent","Chris","Daniel","Edward","Evan","Francis","Howard","James","Kenneth","Norma","Ophelia","Pearl","Phoenix","Prima","XiaoMing"] stuid = 1for name in NameList:StudentDict [stuid]=student(name,stuid)     #student对象的字典stuid = stuid + 1def SelectCourse (StudentList, CourseList):for stu in StudentList:       #每一个学生修几门课CourseNum = random.randint(3,len(CourseList))        #修CourseNum数量的课#随机选,返回列表CourseIndex = random.sample(range(len(CourseList)), CourseNum)for index in CourseIndex:stu.selectCourse(CourseList[index].courseName,CourseList[index].Credit)CourseList[index].SelectThisCourse(stu.StuID)def ExamSimulation (StudentList, CourseList):for day in range(1,6):  #Simulate the datefor cour in CourseList:if(cour.ExamDate==day):  # Hold the exam of course on that dayfor stuID in cour.studentID:for stu in StudentList:if(stu.StuID == stuID):   #student stuID selected this coursestu.TakeExam(cour.courseID)import random
CourseDict={}
StudentDict={}
setupCourse(CourseDict)
setupClass(StudentDict)
SelectCourse(list(StudentDict.values()),list(CourseDict.values()))
ExamSimulation(list(StudentDict.values()),list(CourseDict.values()))SaveToFile = ["ID"," ","Name"," ","Credit"," ","GPA","\n"]
for stu in StudentDict.values():SaveToFile.append(str(stu.StuID))SaveToFile.append(" ")SaveToFile.append(str(stu.name))SaveToFile.append(" ")SaveToFile.append(str(stu.Credit))SaveToFile.append(" ")SaveToFile.append(str(stu.GPA))SaveToFile.append("\n")
f = open("class1.txt","w")
f.writelines(SaveToFile)
f.close()#<程序:查询文件class1.txt中满足某条件的学生信息>
def select(path,col,op,val):f = open(path,"r")colNum = 0if col == "ID": colNum = 0elif col == "Name": colNum = 1elif col == "Credit": colNum = 2elif col == "GPA": colNum = 3f.readline()Info = f.readlines()res = []for e in Info:e = e.strip()eList = e.split()if colNum != 1:exp = eList[colNum] + op + valelse:exp = "'" + eList[colNum] + "'" + op + "'" + val + "'"if eval(exp):res.append(e)f.close()return res
for e in select("class1.txt","Credit",">=","15"):print (e)#<程序:对文件class1.txt中学生进行排序>
def sort(path,col,direct):
#direct表示排序方向,">"为从大到小排序,"<"相反。colNum = 0if col == "Credit": colNum = 2elif col == "GPA": colNum = 3ifrev = Falseif direct == ">":ifrev = Truef = open(path,"r")f.readline()Info = f.readlines()res = []for e in Info:eList = e.split()res.append(eList)res =sorted(res, key=lambda res: res[colNum],reverse=ifrev)
#第三个参数为排序方向f.close()return res
L = [('b',2),('a',1),('c',3),('d',4)]
print (sorted(L, key=lambda x:x[1]))

python学习实例(6)相关推荐

  1. 涵盖 14 大主题!最完整的 Python 学习实例集来了!

    机器学习.深度学习最简单的入门方式就是基于 Python 开始编程实战.最近闲逛 GitHub,发现了一个非常不错的 Python 学习实例集,完全是基于 Python 来实现包括 ML.DL 等领域 ...

  2. python学习实例(4)

    #========================================= #第四章的python程序 #=========================================# ...

  3. python学习实例(7)

    #========================================================= #第8章 信息安全(Information Security)的python程序 ...

  4. python学习实例(3)

    #=================================== #3.4 关于Python的函数调用 #===================================#+++++++ ...

  5. python学习实例(1)

    #====================================== #1.2 计算机编程的基本概念 #======================================#++++ ...

  6. python学习实例(5)

    #============================================ #5.1 计算思维是什么 #======================================== ...

  7. python学习实例(2)

    #=================================== #2.2 不同进制间的转换 #===================================#++++++++++++ ...

  8. Python学习实例(一)温度转换

    1.问题描述 温度的刻画有两个不同体系:摄氏度(Celsius)和华氏度(Fabrenheit).‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪ ...

  9. python学习笔记-练手实例

    1.题目:输出 9*9 乘法口诀表. 程序分析:分行与列考虑,共9行9列,i控制行,j控制列 代码: for i in range(1,10):print ('\r')for j in range(1 ...

最新文章

  1. pandas dataframe 表头_python_库_pandas
  2. SAP MM 初阶之Movement Reason
  3. 查linux还是unix,C、C++判断操作系统是Linux、windows还是Unix
  4. 【通知】深度学习之人脸图像算法重印,欢迎读者支持!
  5. 【转载】java中泛型使用详解
  6. OpenGL学习之路(二)
  7. 租房有深坑?手把手教你如何用R速读评论+科学选房
  8. FIle类和递归方法的使用
  9. CTF之Web训练后篇2
  10. JDBC04 PreparedStatement
  11. 修电脑入门名词及等级划分
  12. 阿虎烧烤的新感悟-O2O你真的会玩吗?
  13. php两个问号??表示什么意思
  14. #9733;关于人类体质弱化的分析
  15. elementUI组件el-table实现分页、勾选、勾选回显功能
  16. VISIO无法插入到word,ppt中
  17. 开源的虚拟化私有云及云管平台
  18. python解释器环境中用于表示上一次运算结果的特殊变量_知到智慧树_中国画基础_作业题库答案...
  19. 人工蜂群算法python_python实现人工蜂群算法
  20. 【Java版oj】逆波兰表达式求值

热门文章

  1. 6个座位办公室最佳位置_四人办公室座次的首选最佳座位在哪儿
  2. table每行自动触发ajax,table.ajax.reload()成功后未触发:function()
  3. 矩阵运算——平移,旋转,缩放
  4. 【转】VS中常用图标提示含义
  5. 【转】DCM(DICOM)医学影像文件格式详解
  6. 【转】Dynamics 365中的事件框架与事件执行管道(Event execution pipeline)
  7. 14工厂方法模式(Factory Method)
  8. Entity Framework 简介
  9. 一步步编写操作系统 48 加载内核1
  10. 与计算机相关的课外活动,课外活动学生论文,关于应用型院校计算机专业课外活动相关参考文献资料-免费论文范文...