Python 字典的使用
#!/usr/local/python3/bin/python3#
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,a_times=[]):
self.name = a_name
self.dob = a_dob
self.time = a_times
def top3(self):
return(sorted(set(sanitize(i) for i in self.time)))
def get_file_data(filename):
try:
with open(filename) as f:
data = f.readline()
templ = data.strip().split(',')
#这里是直接返回类,并且把类可以被传入的参数一并返回。
return (Athlete(templ.pop(0),templ.pop(0),templ))
except IOError as ioerr:
print('File error' + str(ioerr))
return(None)
#由于函数直接返回的是类,这里用任何变量,都会成为返回类的实例化对象。
james1 = get_file_data('james2')
julie1 = get_file_data('julie2')
mikey1 = get_file_data('mikey2')
sarah1 = get_file_data('sarah2')
print(james1.name + "'s fastest time are: " + str(james1.top3()))
print(julie1.name + "'s fastest time are: " + str(julie1.top3()))
print(mikey1.name + "'s fastest time are: " + str(mikey1.top3()))
print(sarah1.name + "'s fastest time are: " + str(sarah1.top3()))
页:
[1]