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