标签:
本文参考Paul Barry所著的《Head First Python》一书,参考代码均可由http://python.itcarlow.ie/站点下载。本文若有任何谬误希望不吝赐教~
说明:data.strip().split(‘,‘)叫做方法串链,strip()应用到data中的数据行,去除字符串中所有的空白符,处理后的结果由第二个方法split(‘,‘)处理,split(‘,‘)表示将结果以,形式分割开,返回列表。with open(james.txt) as jaf: #打开文件data = jaf.readline() #读数据行james =data.strip().split(‘,‘) #将数据转换为列表
def sanitize(time_string):if ‘-‘ in time_string:splitter = ‘-‘if ‘:‘ in time_string:splitter = ‘:‘else:return(time_string)(mins,secs) = time_string.split(splitter)return(mins + ‘.‘ + secs)
等价于clean_mikey = [] #列表创建for each_t in mikey: #迭代clean_mikey.append(sanitize(each_t)) #转换与追加
clean_mikey = [sanitize(each_t) for each_t in mikey]
unique_james = []for each_t in james:if each_t not in unique_james:unique_james.append(each_t)
distances = set(james)
print(sorted(set([sanitize(t)] for t in james]))[0:3])
def get_coach_data(filename):try:with open(filename) as af:return(data.strip().split(‘,‘))except IOError as ioerr:print(‘File error:‘ + str(ioerr))return(None)
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:16Julie 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:59Sarah 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.22Mikey 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
Sarah = get_coach_data(‘sarah2.txt‘)(sarah_name,sarah_dob) = sarah.pop(0),sarah.pop(0)pop(0)调用将删除并返回列表最前面的数据项,并赋值给指定变量姓名和出生日期
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)
(7)类调用与结果输出class Athlete:def __init__(self,a_name,a_dob,a_times=[]):self.name = a_nameself.dob=a_dobself.times=a_timesdef top3(self):return(sorted(set([sanitize(t) for t in self.times]))[0:3])def get_coach_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)
james = get_coach_data(‘james2.txt‘)
标签:
原文地址:http://www.cnblogs.com/I-Tegulia/p/4191658.html