Python 字典和列表的对比应用

时间:2022-03-15 08:53:57

Q:将下列格式的txt文件,打印出该选手的3个最快跑步时间

james2.txt =>“James Lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,2-01,2.01,2:16"
julie2.txt =>Julie Jones,2002-8-17,2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21,3.01,3.02,2:59
mikey2.txt =>Mikey McManus,2002-2-24,2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38,2:40,2.22,2-31
sarah2.txt =>Sarah Sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22

注.pop()方法从指定列表位置删除并返回一个数据项。

1.通过数据抽取到列表来实现

def senitize(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) def get_coach_data(filename):
try:
with open(filename) as f:
data=f.readline()
return(data.strip().split(','))
except IOError as ioerr:
print('File error' +str (ioerr))
return (None) sarah=get_coach_data('sarah2.txt')
(sarah_name,sarah_dob)=sarah.pop(0), sarah.pop(0)
print(sarah_name+"'s fastest times are:"+ str(sorted(set([senitize(t) for t in sarah]))[0:3])) ========== RESTART: C:/Users/eric/Documents/Python/kelly/kelly2.py ==========
Sarah Sweeney's fastest times are:['2.18', '2.21', '2.22']

2. 通过创建字典来实现

def senitize(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) def get_coach_data(filename):
try:
with open(filename) as f:
data=f.readline()
return(data.strip().split(','))
except IOError as ioerr:
print('File error' +str (ioerr))
return (None) sarah=get_coach_data('sarah2.txt')
sarah_data={}
sarah_data['Name']=sarah.pop(0)
sarah_data['DOB']=sarah.pop(0)
sarah_data['Times']=sarah
print(sarah_data['Name']+"'s fastest times are:"+ str(sorted(set([senitize(t) for t in sarah_data['Times']]))[0:3]))

3.将字典和数据打印全部写入函数

def senitize(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) def get_coach_data(filename):
try:
with open(filename) as f:
data=f.readline()
user=data.strip().split(',')
user_data={}
user_data['Name']=user.pop(0)
user_data['DOB']=user.pop(0)
user_data['Times']=user
print(user_data['Name']+"'s fastest times are:"+ str(sorted(set([senitize(t) for t in user_data['Times']]))[0:3]))
except IOError as ioerr:
print('File error' +str (ioerr))
return (None) get_coach_data('sarah2.txt')
get_coach_data('james2.txt')
get_coach_data('mikey2.txt')
get_coach_data('julie2.txt') ========== RESTART: C:/Users/eric/Documents/Python/kelly/kelly2.py ==========
Sarah Sweeney's fastest times are:['2.18', '2.21', '2.22']
James Lee's fastest times are:['2.01', '2.16', '2.22']
Mikey McManus's fastest times are:['2.22', '2.31', '2.38']
Julie Jones's fastest times are:['2.11', '2.23', '2.59']