python脚本编程实例_从零学python系列之数据处理编程实例(一)
要求:分別以james,julie,mikey,sarah四個(gè)學(xué)生的名字建立文本文件,分別存儲(chǔ)各自的成績,時(shí)間格式都精確為分秒,時(shí)間越短成績越好,分別輸出每個(gè)學(xué)生的無重復(fù)的前三個(gè)最好成績,且分秒的分隔符要統(tǒng)一為“.”
數(shù)據(jù)準(zhǔn)備:分別建立四個(gè)文本文件
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
代碼實(shí)現(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語句打開和自動(dòng)關(guān)閉文件
data=f.readline() #從文件中逐行讀取字符
return (data.strip().split(',')) #將字符間的空格清除后,用逗號分隔字符
except IOError as ioerr:
print ('File Error' + str(ioerr)) #異常處理,打印錯(cuò)誤
return (None)
#定義函數(shù)modify_time_format將所有文件中的時(shí)分表達(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和secs
return (mins+ '.' +secs)
#定義函數(shù)get_prev_three返回文件中排名前三的不重復(fù)的時(shí)間成績
def get_prev_three(filename):
new_list=[modify_time_format(each_t) for each_t in get_filedata(filename)] #采用列表推導(dǎo)將統(tǒng)一時(shí)分表達(dá)方式后的記錄生成新的列表
delete_repetition=set(new_list) #采用集合set函數(shù)刪除新列表中重復(fù)項(xiàng),并生成新的集合
in_order=sorted(delete_repetition) #采用復(fù)制排序sorted函數(shù)對無重復(fù)性的新集合進(jìn)行排序
return (in_order[0:3]) #返回列表前三項(xiàng)
# 分別輸出對應(yīng)文件中排名前三的不重復(fù)的時(shí)間成績
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']
總結(jié)
以上是生活随笔為你收集整理的python脚本编程实例_从零学python系列之数据处理编程实例(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python rgb led控件_用树莓
- 下一篇: python+OpenCV图像处理(五)