python学习_数据处理编程实例(一)
目的:用一個實例總結(jié)學(xué)習(xí)到的with語句,函數(shù),列表推導(dǎo),集合,排序,字符分割等內(nèi)容
要求:分別以james,julie,mikey,sarah四個學(xué)生的名字建立文本文件,分別存儲各自的成績,時間格式都精確為分秒,時間越短成績越好,分別輸出每個學(xué)生的無重復(fù)的前三個最好成績,且分秒的分隔符要統(tǒng)一為“.”
數(shù)據(jù)準(zhǔn)備:分別建立四個文本文件
? ? ? ? ? ? ? james.txt ? ??2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22
? ? ? ? ? ? ? julie.txt ? ? ? ?2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21
? ? ? ? ? ? ? mikey.txt ? ? ?2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38
? ? ? ? ? ? ? sarah.txt ? ? ?2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55
代碼實現(xiàn):
import os os.chdir('C:\Python33\HeadFirstPython\hfpy_code\chapter5') #將工作空間修改為文件所在的目錄 #定義函數(shù)get_filedata從文件中取值 def get_filedata(filename):try:with open(filename) as f: #with語句打開和自動關(guān)閉文件data=f.readline() #從文件中逐行讀取字符return (data.strip().split(',')) #將字符間的空格清除后,用逗號分隔字符except IOError as ioerr:print ('File Error' + str(ioerr)) #異常處理,打印錯誤return (None) #定義函數(shù)modify_time_format將所有文件中的時分表達(dá)方式統(tǒng)一為“分.秒” def modify_time_format(time_string):if "-" in time_string:splitter="-"elif ":" in time_string:splitter=":"else:splitter="."(mins, secs)=time_string.split(splitter) #用分隔符splitter分隔字符后分別存入mins和secsreturn (mins+ '.' +secs) #定義函數(shù)get_prev_three返回文件中排名前三的不重復(fù)的時間成績 def get_prev_three(filename):new_list=[modify_time_format(each_t) for each_t in get_filedata(filename)] #采用列表推導(dǎo)將統(tǒng)一時分表達(dá)方式后的記錄生成新的列表delete_repetition=set(new_list) #采用集合set函數(shù)刪除新列表中重復(fù)項,并生成新的集合in_order=sorted(delete_repetition) #采用復(fù)制排序sorted函數(shù)對無重復(fù)性的新集合進(jìn)行排序return (in_order[0:3]) #返回列表前三項 # 分別輸出對應(yīng)文件中排名前三的不重復(fù)的時間成績 print (get_prev_three("james.txt")) print (get_prev_three("julie.txt")) print (get_prev_three("mikey.txt")) print (get_prev_three("sarah.txt"))輸出結(jié)果:
['2.01', '2.22', '2.34'] ['2.11', '2.23', '2.59'] ['2.22', '2.38', '2.49'] ['2.18', '2.25', '2.39']?
參考資料:HeadFirstPython系列書籍chapter 5? ??
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/liutong3310/p/3738372.html
總結(jié)
以上是生活随笔為你收集整理的python学习_数据处理编程实例(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下的mysql修改默认编码
- 下一篇: setTimeout() setInte