标签:style blog color ar strong for 文件 数据 art
无聊,看看《Head First Python》打发一下时间。感觉这本书很一般,可以无聊的时候翻翻。每一章页数很多,但都没讲什么东西。
先看第五章。记录一下知识点:
f.readline():读取文件的一行数据
split():可以将字符串按给定的分隔符拆分为列表
sort():将列表中的数据从小到大排序,原始数据被破坏,传入reverse = True 可以降序
sorted():将列表中的数据从小到大排序,存在复制的空间中,原始数据还在,传入reverse = True 可以降序。注意和sort的用法不同。可以对集合排序,返回一个列表。
集合不可切片,但可以排序。
即 sorted(set(A))[0:3] 正确
set(sorted(A))[0:3] 错误
>>> s = ‘apple,a,day,keeps,the,doctor,away‘ >>> l = s.split(‘,‘) >>> l [‘apple‘, ‘a‘, ‘day‘, ‘keeps‘, ‘the‘, ‘doctor‘, ‘away‘]
>>> d =[2,7,1,4,9,3] >>> d.sort() >>> d [1, 2, 3, 4, 7, 9]
>>> d =[2,7,1,4,9,3] >>> d2 = sorted(d) >>> d2 [1, 2, 3, 4, 7, 9] >>> d [2, 7, 1, 4, 9, 3]
对四组输入数据,输出每组数据不重复的最小的三个数据:
输入 分别从四个txt中得到:
[‘2.01‘, ‘2.01‘, ‘2.22‘, ‘2.34‘, ‘2.34‘, ‘2.45‘, ‘3.01‘, ‘3.10‘, ‘3.21‘]
[‘2.11‘, ‘2.11‘, ‘2.23‘, ‘2.23‘, ‘2.59‘, ‘3.10‘, ‘3.10‘, ‘3.21‘, ‘3.21‘]
[‘2.22‘, ‘2.38‘, ‘2.49‘, ‘3.01‘, ‘3.01‘, ‘3.02‘, ‘3.02‘, ‘3.02‘, ‘3.22‘]
[‘2.18‘, ‘2.25‘, ‘2.39‘, ‘2.54‘, ‘2.55‘, ‘2.55‘, ‘2.55‘, ‘2.58‘, ‘2.58‘]
代码:
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) jaf = open(‘james.txt‘,‘r‘) james = jaf.readline().strip().split(‘,‘) juf = open(‘julie.txt‘,‘r‘) julie = juf.readline().strip().split(‘,‘) mif = open(‘mikey.txt‘,‘r‘) mikey = mif.readline().strip().split(‘,‘) saf = open(‘sarah.txt‘,‘r‘) sarah = saf.readline().strip().split(‘,‘) james_correct = [sanitize(c) for c in james] julie_correct = [sanitize(c) for c in julie] mikey_correct = [sanitize(c) for c in mikey] sarah_correct = [sanitize(c) for c in sarah] print(sorted(set(james_correct))[0:3]) print(sorted(set(julie_correct))[0:3]) print(sorted(set(mikey_correct))[0:3]) print(sorted(set(sarah_correct))[0:3])
>>> ================================ RESTART ================================ >>> [‘2.01‘, ‘2.22‘, ‘2.34‘] [‘2.11‘, ‘2.23‘, ‘2.59‘] [‘2.22‘, ‘2.38‘, ‘2.49‘] [‘2.18‘, ‘2.25‘, ‘2.39‘]
标签:style blog color ar strong for 文件 数据 art
原文地址:http://www.cnblogs.com/dplearning/p/3969972.html