File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Athlete :
2
+ def __init__ (self ,a_name ,a_dob = None ,a_times = []):
3
+ self .name = a_name
4
+ self .dob = a_dob
5
+ self .times = a_times
6
+
7
+ def top3 (self ):
8
+ return (sorted (set ([sanitize (t ) for t in self .times ]))[0 :3 ])
9
+
10
+ def add_time (self ,time ):
11
+ self .times .append (time )
12
+
13
+ def add_times (self ,time = []):
14
+ #for t in time:
15
+ #self.times.append(t)
16
+ self .times .extend (time )
17
+
18
+
19
+
20
+
21
+ def sanitize (time_string ): #序列化得到的无规则数据,将其格式化为 mins.secs 的格式
22
+ if '-' in time_string :
23
+ splitter = '-'
24
+ elif ':' in time_string :
25
+ splitter = ':'
26
+ else :
27
+ return (time_string )
28
+ (mins ,secs )= time_string .split (splitter )
29
+ return (mins + '.' + secs )
30
+
31
+ def load_from_file (filename ): #读取文件的一行(这个文件只有一行,多行咋办)
32
+ try :
33
+ with open (filename ) as f :
34
+ data = f .readline ()
35
+ templ = data .strip ().split (',' )
36
+ return (Athlete (templ .pop (0 ),templ .pop (0 ),templ ))#返回一个Athlete对象
37
+ except IOError as err :
38
+ print ('File Error: ' + str (err ))
39
+ return (None )
40
+
41
+ sarah = load_from_file ('sarah2.txt' )
42
+
43
+ print (sarah .name + "'s fastest times are: " + str (sarah .top3 ()))
44
+
45
+ sarah .add_time ('2:20' )
46
+ print (sarah .times )
47
+
48
+ sarah .add_times (['2:15' ,'1:20' ,'2-33' ])
49
+ print (sarah .times )
50
+
51
+ print (sarah .name + "'s fastest times are: " + str (sarah .top3 ()))
You can’t perform that action at this time.
0 commit comments