#!/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)
def get_file_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)
sarah1 = get_file_data('sarah2')
#这里是将列表中前两项数据,人名和生日使用pop弹出到sarah_name,sarah_dob两个变量中。
(sarah_name,sarah_dob) = sarah1.pop(0),sarah1.pop(0)
#这里要做字符串拼接,所以后面的序列处理完之后,需要使用str()转换成字符串。
print(sarah_name + "'s fastest times are:" + str(sorted(set([ sanitize(i) for i in sarah1 ]))[0:3]))
输出结果:
Sarah Sweeney's fastest times are:['2.18', '2.25', '2.39']
#!/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)
def get_file_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)
sarah1 = get_file_data('sarah2')
#定义字典
sarah_dic=dict()
#将列表中前两个数据项,弹出保存到字典对应的键上。
sarah_dic['name'] = sarah1.pop(0)
sarah_dic['dob'] = sarah1.pop(0)
#姓名和日期都弹出了,sarah1里面剩下的就是时间数据了,保存在sarah_dic字典中,键为time;
sarah_dic['time'] = sarah1
print(sarah_dic['name'] + "'s fastest time are: " + str(sorted(set([sanitize(i) for i in sarah1]))[0:3]))
#!/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)
def get_file_data(filename):
try:
with open(filename) as f:
data = f.readline()
templ = data.strip().split(',')
return({'name':templ.pop(0),
'dob':templ.pop(0),
'time':str(sorted(set([sanitize(i) for i in templ]))[0:3])})
except IOError as ioerr:
print('File error' + str(ioerr))
return(None)
print(james1['name'] + "'s fastest time are: " + james1['time'])
print(julie1['name'] + "'s fastest time are: " + julie1['time'])
print(mikey1['name'] + "'s fastest time are: " + mikey1['time'])
print(sarah1['name'] + "'s fastest time are: " + sarah1['time'])
输出结果:
难点:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def get_file_data(filename):
try:
with open(filename) as f:
data = f.readline()
templ = data.strip().split(',')
#可以看到这里是返回字典了,发现连字典名都没有,直接返回的是键和对应的数据。
return({'name':templ.pop(0),
'dob':templ.pop(0),
'time':str(sorted(set([sanitize(i) for i in templ]))[0:3])})
except IOError as ioerr:
print('File error' + str(ioerr))
return(None)