6 定制数据对象:数据结构自定义
打包代码与数据
james2.txt:
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:16
julie2.txt:
Julie 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:59
mikey2.txt:
Mikey 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
sarah2.txt :
Sarah 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.22
现在要通过函数get_coach_data()来读取sarah2.txt,并完成排序的工作,代码如下:
>>> sarah=get_coach_data('sarah2.txt')
>>> (sarah_name,sarah_dob)=sarah.pop(0),sarah.pop(0)
>>> print(sarah_name+"'s fastest times are:"+str(sorted(set([sanitize(t)for t in sarah]))[0:3]))
输出:Sarah Sweeney's fastest times are:['2.18', '2.21', '2.22']
上面用到了pop(0),这个方法会删除并返回最前面的数据项;两个pop(0)调用则会删除前两个数据值,并把它们复制给指定的变量。
以上方法适用于数据较少的情况,如果数据量大了,就需要引入字典关联。
使用字典关联数据
字典是一个内置的数据结构(内置与Python中),允许将数据与键关联,这个键和数据库的键是相同的概念。
这样可以使内存中的数据与实际数据的结构保持一致,其他语言中可能称为:映射,散列,关联数组。
注:每个字典都有一个Name和一个Occupations列表列表。
有两种方法可以创建字典:
一:使用大括号创建;
如:cleese = {}
二:使用工厂函数创建;
如:palin =dict()
此外,可用type(cleese),type(palin)来查看字典的类型。
>>> cleese['Name']='John Cleese' #创建Name列表
>>> cleese['Occuptions']=['actor','comedian','writer','film producer'] #创建Occuptions列表
>>> palin={'Name':'Michael Palin','Occupations':['comedian','actor','writer','tv']} #创建字典内容,需注意palin字典是一次性同时创建的
>>> palin['Name']
'Michael Palin'
>>> cleese['Occuptions']
['actor', 'comedian', 'writer', 'film producer']
>>> cleese['Occuptions'][-1]
'film producer'
接下来,给palin和cleese增加出生地址信息:
>>> palin['Birthplace']="Broomhill,Sheffield,Endland"
>>> cleese['Birthplace']="Weston-super-Mare,North somerset,England"
>>> palin
{'Birthplace': 'Broomhill,Sheffield,Endland', 'Occupations': ['comedian', 'actor', 'writer', 'tv'], 'Name': 'Michael Palin'}
>>> cleese
{'Birthplace': 'Weston-super-Mare,North somerset,England', 'Occuptions': ['actor', 'comedian', 'writer', 'film producer'], 'Name': 'John Cleese'}
接下来,修改方法get_coach_data()方法,加入字典的创建和使用:
>>> def get_coach_data1(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) >>> james=get_coach_data1('james2.txt') >>> print(james['Name']+"'s fastest times are:"+ james['Times']) James Lee's fastest times are:['2.01', '2.16', '2.22'] >>> julie=get_coach_data1('julie2.txt') >>> print(julie['Name']+"'s fastest times are:"+ julie['Times']) Julie Jones's fastest times are:['2.11', '2.23', '2.59'] >>> mikey=get_coach_data1('mikey2.txt') >>> print(mikey['Name']+"'s fastest times are:"+ mikey['Times']) Mikey McManus's fastest times are:['2.22', '2.31', '2.38'] >>> print(sarah['Name']+"'s fastest times are:"+ sarah['Times']) >>> sarah=get_coach_data1('sarah2.txt') >>> print(sarah['Name']+"'s fastest times are:"+ sarah['Times']) Sarah Sweeney's fastest times are:['2.18', '2.21', '2.22']