Skip to content

Commit 2dc966d

Browse files
author
Fox.Lee
committed
为Athlete 类增加append 和extend 的方法
其实athlete 用到了很多 list的方法,
1 parent be5ddf2 commit 2dc966d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

17-p199.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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()))

0 commit comments

Comments
 (0)