首页 > 代码库 > [Head First Python]5.推导数据
[Head First Python]5.推导数据
读取4个文件内容,格式化数据,升序,显示每个文件前3个数据
julie.txt
2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21
james.txt
2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22
sarah.txt
2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55
mikey.txt
2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38
chapter5.py
1 def get_coach_data(filename): 2 try: 3 with open(filename) as f: 4 data =http://www.mamicode.com/ f.readline() 5 return ( data.strip().split(‘,‘)) 6 except IOError as err: 7 print(‘File err:‘ + str(err)) 8 return(None) 9 10 def sanitize(time_string):11 if ‘-‘ in time_string:12 splitter = ‘-‘13 elif ‘:‘ in time_string:14 splitter = ‘:‘15 else:16 return(time_string)17 18 (mins, secs) = time_string.split(splitter)19 return(mins + ‘.‘ + secs)20 21 try:22 julie = get_coach_data(‘julie.txt‘)23 james = get_coach_data(‘james.txt‘)24 sarah = get_coach_data(‘sarah.txt‘)25 mikey = get_coach_data(‘mikey.txt‘) 26 27 print( sorted( set ([sanitize(s) for s in julie]) )[0:3] )28 print( sorted( set ([sanitize(s) for s in james]) )[0:3] )29 print( sorted( set ([sanitize(s) for s in sarah]) )[0:3] )30 print( sorted( set ([sanitize(s) for s in mikey]) )[0:3] )31 32 except IOError as err:33 print("file error" + str(err))
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。