james的跑步时间存储为james.txt,内容如下:
2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22
写一个函数,把里面的“-” 和“:”都改为 “ . "
import os
import sys
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) #拼接出新的格式
with open('james.txt') as jaf:
data = jaf.readline()
james = data.strip().split(',') #去掉空白符
clean_james=[]
for each_t in james:
clean_james.append(sanitize(each_t)) #去掉“-”和“:”
james2=sorted(james)
print("the_oldlist: " , james) #输出原文
print("Sorted list: " , james2) #输出仅原文排序
print("Correct list: " , sorted(clean_james)) #输出原文去掉“-”和“:”,再排序
输出结果:
RESTART: C:/Users/ThinkPad/AppData/Local/Programs/Python/Python36-32/chapter5/chapter5-try.py
the_oldlist: ['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22']
Sorted list: ['2-22', '2-34', '2.34', '2.45', '2:01', '2:01', '3.01', '3:10', '3:21']
Correct list: ['2.01', '2.01', '2.22', '2.34', '2.34', '2.45', '3.01', '3.10', '3.21']
>>>
其中打开文件那三行可以抽象出,及其用法和打印不重复的有序头三个时间。
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)
james4=get_coach_data('james.txt')
print(sorted(set(sanitize (t) for t in james4))[0:3])细节:
http://www.jianshu.com/p/634136c2e2a2
本文介绍了一个Python程序,用于读取存储在文本文件中的跑步成绩数据,并通过编写一个函数来清理这些数据,将其中的“-”和“:”替换为“.”,以便于进行比较和排序。此外,还展示了如何获取不重复且已排序的成绩列表的前三个最佳成绩。
9236

被折叠的 条评论
为什么被折叠?



