從零學python系列之資料處理編程執行個體(一)_python

來源:互聯網
上載者:User

要求:分別以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和secs
    return (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']

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.