定制数据对象--打包代码与数据

来源:互联网 发布:常用抓包软件 编辑:程序博客网 时间:2024/05/29 05:56

例子:

所需数据:Head First Python第六部分中的数据sarah2.txt。

需求:展示跑步者的名字及其最快的三个时间。

sarah = nester.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([nester.sanintize(t) for t in sarah]))[0:3]))

一共有三个变量:sarah,sarah_name,sarah_dob。以此,所有选手都需要有三个变量。


有没有一种数据结构,可以使得一个选手的所有数据与单个的变量关联。


Python字典。将数据值与键关联。


字典是一个内置的数据结构(内置于Python中)允许将数据与键而不是数字关联。这样可以使内存中的数据与实际数据的结构保持一致。

一些简单的例子:

>>> cleese={}>>> palin=dict()>>> type(cleese)<class 'dict'>>>> type(palin)<class 'dict'>>>> cleese['Name']='John Cleese'>>> cleese['Occupations']=['actor','comedian','writer']>>> palin={'Name':'Michael Palin','Occupations':['comedian','writer','tv']}>>> palin['Name']'Michael Palin'>>> cleese['Occupations'][-1]'writer'>>> palin['BirthPlace']="Broomhill,Sheffield,England">>> cleese['BirthPlace']="Weston-super-Mare,North Somerset,England">>> palin{'Name': 'Michael Palin', 'Occupations': ['comedian', 'writer', 'tv'], 'BirthPlace': 'Broomhill,Sheffield,England'}>>> cleese{'Name': 'John Cleese', 'Occupations': ['actor', 'comedian', 'writer'], 'BirthPlace': 'Weston-super-Mare,North Somerset,England'}


Sarah的例子用字典:

sarah = nester.get_coach_data('sarah2.txt')sarah_zi={}sarah_zi['Name']=sarah.pop(0)sarah_zi['Dob']=sarah.pop(0)sarah_zi['Time']=sarahprint(sarah_zi['Name']+"'s fastest times are"+str(sorted(set([nester.sanitize(t) for t in sarah_zi['Time']]))[0:3]))


算法改进:将get_coach_data函数中返回的列表改为直接返回字典的形式,而且把最快的三个时间的处理也放在其中。

def get_coach_data_new(filename):    try:        with open(filename) as f:            data = f.readline().strip().split(',')            data_dict = {}            data_dict['Name']=data.pop(0)            data_dict['Dob']=data.pop(0)            data_dict['Time']=sorted(set([sanitize(t) for t in data]))[0:3]        return data_dict    except IOError as ioerr:        print('File error:'+str(ioerr))        return(None)

运行:

sarah = {}sarah = nester.get_coach_data_new("sarah2.txt")
sarah

运行结果:

{'Name': 'Sarah Sweeney', 'Dob': '2002-6-17', 'Time': ['2.18', '2.21', '2.22']}



0 0
原创粉丝点击