forked from foxli180/HeadFirstPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
17-p199.py
51 lines (38 loc) · 1.48 KB
/
17-p199.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Athlete:
def __init__(self,a_name,a_dob=None,a_times=[]):
self.name = a_name
self.dob= 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):
self.times.append(time)
def add_times(self,time=[]):
#for t in time:
#self.times.append(t)
self.times.extend(time)
def sanitize(time_string): #序列化得到的无规则数据,将其格式化为 mins.secs 的格式
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins,secs)=time_string.split(splitter)
return(mins+'.'+secs)
def load_from_file(filename): #读取文件的一行(这个文件只有一行,多行咋办)
try:
with open (filename) as f:
data = f.readline()
templ = data.strip().split(',')
return (Athlete(templ.pop(0),templ.pop(0),templ))#返回一个Athlete对象
except IOError as err:
print('File Error: '+str(err))
return (None)
sarah = load_from_file('sarah2.txt')
print(sarah.name +"'s fastest times are: "+str(sarah.top3()))
sarah.add_time('2:20')
print(sarah.times)
sarah.add_times(['2:15','1:20','2-33'])
print(sarah.times)
print(sarah.name +"'s fastest times are: "+str(sarah.top3()))