[Head First Python]6. 定制数据对象:打包代码与数据
相同功能,演进实现
数据文件
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
1- 返回dict
return({'Name':data_list.pop(0),
'DOB':data_list.pop(0),
'Time':str( sorted( set([sanitize(t) for t in data_list] ) )[0:3])})
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) def get_coach_data(filename):
try:
with open(filename) as f:
data = f.readline()
data_list = data.strip().split(',')
return({'Name':data_list.pop(0),
'DOB':data_list.pop(0),
'Time':str( sorted( set([sanitize(t) for t in data_list] ) )[0:3])})
except IOError as err:
print("file err:" + str(err))
return(none) julie = get_coach_data('julie2.txt')
james = get_coach_data('james2.txt')
sarah = get_coach_data('sarah2.txt')
mikey = get_coach_data('mikey2.txt') print( julie['Name'] + "'s faster time are:" + julie['Time'])
print( james['Name'] + "'s faster time are:" + james['Time'])
print( sarah['Name'] + "'s faster time are:" + sarah['Time'])
print( mikey['Name'] + "'s faster time are:" + mikey['Time'])
2- 返回类 return ( Athlete(datalist.pop(0), datalist.pop(0), datalist))
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) class Athlete:
def __init__(self, a_name, a_dob = None, a_time = []):
self.name = a_name
self.dob = a_dob
self.times = a_time def top3(self):
return( sorted(set([sanitize(t) for t in self.times]))[0:3] ) def add_time(self,time_value):
self.times.append(time_value) def add_times(self,list_of_times):
self.times.extend(list_of_times) def get_coach_data(filename):
try:
with open(filename) as f:
data = f.readline();
datalist = data.strip().split(',')
return ( Athlete(datalist.pop(0), datalist.pop(0), datalist))
except IOError as err:
print('file err:' + str(err))
return(none) julie = get_coach_data('julie2.txt')
james = get_coach_data('james2.txt')
sarah = get_coach_data('sarah2.txt')
mikey = get_coach_data('mikey2.txt') print(julie.name + "'s faster times are:" + str(julie.top3()))
print(james.name + "'s faster times are:" + str(james.top3()))
print(sarah.name + "'s faster times are:" + str(sarah.top3()))
print(mikey.name + "'s faster times are:" + str(mikey.top3())) vera = Athlete('vera vi')
vera.add_time('1.30')
print(vera.top3())
vera.add_times(['1.00','0.3','1.2'])
print(vera.top3())
3- 继承python内置list
class Athletelist(list):
def __init__(self, a_name, a_dob = None, a_times = []):
list.__init__([])
self.name = a_name
self.dob = a_dob
self.extend(a_times)
def top3(self):
return( sorted( set([sanitize(t) for t in self] ) )[0:3]) 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) #vera = Athletelist("vera vi")
#vera.append('1.31')
#print(vera.top3())
#vera.extend(["1","2","0"])
#print(vera.top3()) def get_coach_data(filename):
try:
with open(filename) as f:
data = f.readline();
datalist = data.strip().split(',')
return ( Athletelist(datalist.pop(0), datalist.pop(0), datalist))
except IOError as err:
print('file err:' + str(err))
return(none) julie = get_coach_data('julie2.txt')
james = get_coach_data('james2.txt')
sarah = get_coach_data('sarah2.txt')
mikey = get_coach_data('mikey2.txt') print(julie.name + "'s faster times are:" + str(julie.top3()))
print(james.name + "'s faster times are:" + str(james.top3()))
print(sarah.name + "'s faster times are:" + str(sarah.top3()))
print(mikey.name + "'s faster times are:" + str(mikey.top3()))
[Head First Python]6. 定制数据对象:打包代码与数据的更多相关文章
- ch6-定制数据对象(打包代码和数据)
为了看出数据属于哪个选手,教练向各个选手的数据文件中添加了标识数据:选手全名,出生日期,计时数据. 例如:sarah文件的数据更新为: Sarah Sweeney,2002-6-17,2:58,2.5 ...
- Tcp 数据对象传输接口对象设计
输入是一个对象inputObj,接口对象.Send(inputObj),对端接收之后解包成outputObj(与inputObj应相同),触发onPackageReceive事件 事件 public ...
- Oracle 常用的SQL语法和数据对象
一.数据控制语句 (DML) 部分 1.INSERT (往数据表里插入记录的语句) INSERT INTO 表名(字段名1, 字段名2, ……) VALUES ( 值1, 值2, ……); INSE ...
- Oracle---常用SQL语法和数据对象
1.INSERT (往数据表里插入记录的语句) INSERT INTO 表名(字段名1, 字段名2, ……) VALUES ( 值1, 值2, ……); INSERT INTO 表名(字段名1, 字 ...
- mysql数据对象
学习目标: 了解掌握常见的几种数据库对象 学会如何创建具体的数据对象 mysql 常见的数据对象有哪些: DataBase/Schema Table Index View/Trigger/ ...
- 用python pickle库来存储数据对象
pickling有一个更常用的叫法是serialization,它是指把python对象转化成字节流byte stream, unpickling就是把byte stream转换成对象.python的 ...
- python学习_应用pickle模块封装和拆封数据对象
学习文件数据处理的时候了解到有pickle模块,查找官方文档学习了一些需要用到的pickle内容. 封装是一个将Python数据对象转化为字节流的过程,拆封是封装的逆操作,将字节文件或字节对象中的字节 ...
- python pickle模块的使用/将python数据对象序列化保存到文件中
# Python 使用pickle/cPickle模块进行数据的序列化 """Python序列化的概念很简单.内存里面有一个数据结构, 你希望将它保存下来,重用,或者发送 ...
- Python学习笔记 | 关于python数据对象 hashable & unhashable 的理解
文章目录 写在前面 hashable & unhashable mutable & immutable 实例检测 后续思考 参考文章 写在前面 Hash(哈希.散列)是一个将大体量数据 ...
随机推荐
- overflow应用随记
今天在帮别人改页面时遇到了overflow属性,虽然对他已经比较熟悉了,但还是去专门查找了一下.和大家分享下. overflow 属性规定当内容溢出元素框时发生的事情. 这个属性定义溢出元素内容区的内 ...
- php中的时区设置
date_default_timezone_set('PRC'); 设置为中国时区
- 滑雪(POJ 1088 记忆化搜索)
滑雪 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 88094 Accepted: 33034 Description ...
- mongoexport导出数据
mongoexport用法: /***** Export MongoDB data to CSV, TSV or JSON files.options: --help ...
- Win7+CentOS双系统,最清晰细致的教程!
Win7的系统下安装CentOS,实现双系统切换使用的目的,希望对大家有帮助. 注意: 1.由于涉及到对硬盘操作,请妥善备份数据,避免损失. 2.我的步骤是绝对正确和缺一不可的,大家一定要按照我的操作 ...
- CS找工作好文章
我的美国CS面试经验分享 -- 转载 怎样花两年时间去面试一个人 上面列出了一些比较好的书单 cs土硕找工作总结(二) 笔试面试准备http://blog.renren.com/blog/221227 ...
- !!!!OpenWrt系列教程汇总
OpenWrt FAQ https://dev.openwrt.org.cn/wiki/faqs OpenWrt编译教程 完全新手教程:openwrt编译全过程(sse) 直接编译出带中文的openw ...
- bzoj1734 [Usaco2005 feb]Aggressive cows 愤怒的牛
Description Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stal ...
- WEB打印插件Lodop
Lodop.C-Lodop使用说明及样例 Lodop(标音:劳道谱,俗称:露肚皮)是专业WEB控件,用它既可裁剪输出页面内容,又可用程序代码直接实现 复杂打印.控件功能强大,却简单易用,所有调用如 ...
- 关于Tcp三次握手的思考
一.为什么不能使两次握手,两次握手就应该可以保证线路的畅通? 1) 只能建立一个方向的连接,称为半连接 记住TCP是全双工的. A向B发出请求,同时收到B的确认,这时只有A.B知道A到B的连接成功了. ...