定制数据对象--打包代码与数据
来源:互联网 发布:常用抓包软件 编辑:程序博客网 时间: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 = 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
- 定制数据对象--打包代码与数据
- HeadFirstPython---------(四)第六章(定制数据对象__打包代码与数据)
- 定制数据对象
- python定制数据对象
- Head First Python(定制数据对象)
- 对象数据与基本数据
- Dspace元数据与上传工作流定制
- springmvc与ajax传递单个对象代码、map形式数据,前端显示数据代码
- 区分代码与数据
- python系列学习四——定制数据对象
- 《head first python》——定制数据对象
- 【Head First Python-第六章-定制数据对象】学习笔记
- 当类中含有logging等流数据时,使用pickle打包与装载类对象数据
- Java 代码中添加元数据 定制注释
- Java 代码中添加元数据 定制注释
- 定制数据层
- 定制数据层
- 定制数据层
- RMAN备份与恢复系列之非系统表空间恢复
- Android微信第三方登录(个人笔记
- 怎么用VC6.0建立控制台程序
- 学习淘淘商城第五十三课(使用JMail来发送邮件)
- 通用对话框,调用另一个窗体,查找对话框
- 定制数据对象--打包代码与数据
- hash与动态数组
- IO(字符流)
- lintcode(511)交换链表当中两个节点
- csdn一天最多发博文20篇
- 媒体和相机:相机 API
- 流形学习
- 中国金融体系(金融机构,金融市场,金融基础设施)
- Java面向对象及特性理解