Python筆記(六):推導資料,python筆記推導資料

來源:互聯網
上載者:User

Python筆記(六):推導資料,python筆記推導資料

(一)  準備工作

建立1個檔案記錄運動員的跑步成績

james.txt 

2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22

(二)  要求

在螢幕上輸出運動員最好的3個成績

(三)  思考該怎麼實現

(1)通過open()建立檔案對象

(2)通過open()的readline方法讀取檔案資料(這個輸出的是一行資料)

(3)想要擷取最好的3個成績,那麼首先要將資料分割(通過split分割成績)

(4)對分割後的列表資料進行排序

(5)2-34,3:21,2.34中間的符號不一致會導致排序出問題(-和,和.),所以還需要一個函數將它們修改成一致的。

(四)  具體實現

(1)   主程式碼

from FirstPython import the_list as tl
#匯入the_list模組
the_james = tl.dsfile('F:\Python\Python檔案\james.txt')
#調用the_list模組的dsfile()函數讀取檔案資料
print(sorted(set([tl.sanitize(t) for t in the_james]),reverse=True)[0:3])
#sorted()預設升序排序,reverse=True時降序排序
#set()重複資料刪除項,返回新的集合對象(無序的)
#[0:3]訪問列表第0項、第1項、第2項的資料
'''
[tl.sanitize(t) for t in the_james] 等價於下面的代碼(迭代處理the_james列表,返回一個新的列表)
new_list = []
for t in the_james:
    new_list.append(tl.sanitize(t))
'''

(2)    the_list模組代碼

def sanitize(time_str):
    #傳入資料,將'-'和':'修改為'.'並返回,否則直接返回
   
if '-' in time_str:
        (x,y) = time_str.split('-',1)
        return(x+"."+y)
    elif ':' in time_str:
        (x,y) = time_str.split(':',1)
        return (x + "." + y)
    else:
        return(time_str)

def dsfile(the_file):
    #傳入一個檔案,返迴文件第一行資料
 
with open(the_file) as james_file:
    each_line = james_file.readline().strip().split(',')
    #strip()去除字串中不需要的空白符,不加這個列表資料會多一個\n
    #split(',')根據,分割資料,返回一個列表
   
return each_line

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.