python学习_数据处理编程实例(一)
生活随笔
收集整理的這篇文章主要介紹了
python学习_数据处理编程实例(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目的:用一個實例總結學習到的with語句,函數,列表推導,集合,排序,字符分割等內容
要求:分別以james,julie,mikey,sarah四個學生的名字建立文本文件,分別存儲各自的成績,時間格式都精確為分秒,時間越短成績越好,分別輸出每個學生的無重復的前三個最好成績,且分秒的分隔符要統一為“.”
數據準備:分別建立四個文本文件
? ? ? ? ? ? ? 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
代碼實現:
import os os.chdir('C:\Python33\HeadFirstPython\hfpy_code\chapter5') #將工作空間修改為文件所在的目錄 #定義函數get_filedata從文件中取值 def get_filedata(filename):try:with open(filename) as f: #with語句打開和自動關閉文件data=f.readline() #從文件中逐行讀取字符return (data.strip().split(',')) #將字符間的空格清除后,用逗號分隔字符except IOError as ioerr:print ('File Error' + str(ioerr)) #異常處理,打印錯誤return (None) #定義函數modify_time_format將所有文件中的時分表達方式統一為“分.秒” 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) #定義函數get_prev_three返回文件中排名前三的不重復的時間成績 def get_prev_three(filename):new_list=[modify_time_format(each_t) for each_t in get_filedata(filename)] #采用列表推導將統一時分表達方式后的記錄生成新的列表delete_repetition=set(new_list) #采用集合set函數刪除新列表中重復項,并生成新的集合in_order=sorted(delete_repetition) #采用復制排序sorted函數對無重復性的新集合進行排序return (in_order[0:3]) #返回列表前三項 # 分別輸出對應文件中排名前三的不重復的時間成績 print (get_prev_three("james.txt")) print (get_prev_three("julie.txt")) print (get_prev_three("mikey.txt")) print (get_prev_three("sarah.txt"))輸出結果:
['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? ??
?
?
?
轉載于:https://www.cnblogs.com/liutong3310/p/3738372.html
總結
以上是生活随笔為你收集整理的python学习_数据处理编程实例(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下的mysql修改默认编码
- 下一篇: setTimeout() setInte