引入字典---利用字典来对应同类型的数据与key
#定义sanitize函数格式化数据 def sanitize(time_string): try: if '-' in time_string: splitter = '-' elif ':' in time_string: splitter = ':' else: return(time_string) #返回格式化的数据 (mins, secs) = time_string.split(splitter) return(mins + '.'+secs) except: print ('values error') #定义函数get_coach_data将文档转化为数列 def get_coach_data(filename): try: with open (filename) as f: data = f.readline() templ = data.strip().split(',')
#返回一个字典 return({ 'Name' :templ.pop(0), 'DOB' :templ.pop(0), 'Times' :str(sorted(set([sanitize(t) for t in templ]))[0:3])}) except IOError as ioerr: print('File error:' + str(ioerr)) #报错 return(None) #并返回None,指示失败 #输出 james = get_coach_data( 'james2.txt' ) #将字典赋至给变量 print(james[ 'Name' ] + "'s fastest time are: " + james[ 'Times' ]) julie2 = get_coach_data( 'julie2.txt' ) print(julie2[ 'Name' ] + "'s fastest time are: " + julie2[ 'Times' ]) sarah2 = get_coach_data( 'sarah2.txt' ) print(sarah2[ 'Name' ] + "'s fastest time are: " + sarah2[ 'Times' ]) mikey2 = get_coach_data( 'mikey2.txt' ) print(mikey2[ 'Name' ] + "'s fastest time are: " + mikey2[ 'Times' ])
#创建字典的两种方法 new_d = {} new_d = dict() #填充字典的两种方法 new_d['name'] = 'liz' new_d = { 'name' : 'liz'}