定製資料物件2
阿新 • • 發佈:2020-09-16
# Author kevin_hou def sanitize(time_string): #將時間格式化為統一字串格式 if '-' in time_string: splitter = '-' elif ':' in time_string: splitter = ':' else: return(time_string) (mins, secs) = time_string.split(splitter) return(mins + '.' + secs) class Athlete: #定義父類 def __init__(self, a_name, a_dob=None, a_times=[]): self.name = a_name self.don = a_dob self.times = a_times def top3(self): #定義篩選前三項子函式 return (sorted(set([sanitize(t) for t in self.times]))[0:3]) def add_time(self, time_value): #將1個額外的計時值追加到選手的計時資料 self.times.append(time_value) def add_times(self, list_of_times): #用1個或多個計時值(提供為1個列表) self.times.extend(list_of_times) #來擴充套件1個選手的計時資料 def get_coah_data(filename): #開啟檔案獲取資料 try: with open(filename) as f: data = f.readline() temp1 = data.strip().split(',') # return ({'Name': temp1.pop(0), # 'DOB': temp1.pop(0), # 'Times': str(sorted(set([sanitize(t) for t in temp1]))[0:3])}) return Athlete(temp1.pop(0), temp1.pop(0), temp1) except IOError as ioerr: print('File error:' +str(ioerr)) return(None) james = get_coah_data('james2.txt') sarah = get_coah_data('sarah2.txt') # print(james['Name'] + "'s fastest times are:" + james['Times']) print(james.name + "'s fastest times are:" + str(james.top3())) #James Lee's fastest times are:[' 2.34', '2.01', '2.22'] print(sarah.name + "'s fastest times are:" + str(sarah.top3())) #Sarah Sweeney's fastest times are:['2.18', '2.25', '2.39'] vera = Athlete('Vera Vi') vera.add_time('1.31') print(vera.top3()) #['1.31'] vera.add_times(['2.22', "1;21", '2:22']) print(vera.top3())