打包代码与数据

数据结构要与数据匹配,数据结构影响代码的复杂性
 
列表
集合
字典
#创建与初始化
cleese={}
cleese2=dict()
cleese["name"]="luocaimin"
cleese["times"]=["2.2","2:25","2.12","2.08"]
palin={"Name":"Michael Palin","Occupation":["comedian","actor","writer","tv"]}
print(palin["Occupation"][-1])
 
eg:
import os

FileName="F:\\book\\python\\headfirst python book&&code\\code\\chapter6\\data\\sarah2.txt"

def sanitize(time_string):
    if ":" in time_string:
        min,sec=time_string.split(":")
    elif "-" in time_string:
        min,sec=time_string.split("-")

if 'min' in locals():
        return min+"."+sec
    else:
        return time_string

def get_coach_data(fileName):
        try:
                with open(fileName) as f:
                    data=f.readline().strip().split(',')
          #字典的创建与初始化
                cachData={"name":data.pop(0),"dob":data.pop(0),"times":str([sorted(set([sanitize(item) for item in data]))[0:3]])}
                return cachData
        except IOError as err:
                print("File error "+str(err))
                return (None)

sportRecord=get_coach_data(FileName)
#字典的访问

print(sportRecord["name"]+"'s fastest times are:"+str(sportRecord["times"]))
 
 
类:
 
 
import os

FileName="F:\\book\\python\\headfirst python book&&code\\code\\chapter6\\data\\sarah2.txt"

def sanitize(time_string):
     if ":" in time_string:
          min,sec=time_string.split(":")
     elif "-" in time_string:
          min,sec=time_string.split("-")
    
     if 'min' in locals():
          return min+"."+sec
     else:
          return time_string

class Athlete:
     #__init__是每个类必须具有的方法,用来初始化实例
     #每个方法的第一个参数必须是self,调用的时候会把发起调用的实例赋值给self
     def __init__(self,a_name,a_dob=None,a_times=[]):
          self.name=a_name
          self.dob=a_dob
          self.times=a_times
     def top3(self):
          return sorted(set([sanitize(item) for item in self.times]))[0:3]
     def add_time(self,t):
          self.times.append(t)
     def add_times(self,ts):
          self.times.extend(ts)

def get_coach_data(fileName):
     try:
          with open(fileName) as f:
               data=f.readline().strip().split(',')
          return Athlete(data.pop(0),data.pop(0),data)
     except IOError as err:
          print("File error "+str(err))
          return (None)

sportRecord=get_coach_data(FileName)

print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))

sportRecord.add_time("2.17")
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))

sportRecord.add_times(["2.15","2.16"])
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))

 
BIF:type()
 
 
 
 
 
 
 
 
继承:可以从任何内置类型继承,支持多继承
 
import os

FileName="F:\\book\\python\\headfirst python book&&code\\code\\chapter6\\data\\sarah2.txt"

def sanitize(time_string):
     if ":" in time_string:
          min,sec=time_string.split(":")
     elif "-" in time_string:
          min,sec=time_string.split("-")
    
     if 'min' in locals():
          return min+"."+sec
     else:
          return time_string

"""
class Athlete:
     def __init__(self,a_name,a_dob=None,a_times=[]):
          self.name=a_name
          self.dob=a_dob
          self.times=a_times
     def top3(self):
          return sorted(set([sanitize(item) for item in self.times]))[0:3]
     def add_time(self,t):
          self.times.append(t)
     def add_times(self,ts):
          self.times.extend(ts)

"""
#继承的语法
class Athlete(list):
        def __init__(self,a_name,a_dob=None,a_times=[]):
                #调用父类的方法
                list.__init__([])
                self.extend(a_times)
                self.name=a_name
                self.dob=a_dob
               
        def top3(self):
                return sorted(set([sanitize(item) for item in self]))[0:3]

def get_coach_data(fileName):
     try:
          with open(fileName) as f:
               data=f.readline().strip().split(',')
          return Athlete(data.pop(0),data.pop(0),data)
     except IOError as err:
          print("File error "+str(err))
          return (None)

sportRecord=get_coach_data(FileName)

print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))

sportRecord.append("2.17")
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))

sportRecord.extend(["2.15","2.16"])
print(sportRecord.name+"'s fastest times are:"+str(sportRecord.top3()))

python学习五的更多相关文章

  1. Python学习(五) Python数据类型:列表(重要)

    列表: list是一组有序项目的数据结构. 列表是可变类型的数据,列表用[]进行表示,包含了多个以","分隔的项目. list=[] type(list) //<type ' ...

  2. Python学习五|集合、布尔、字符串的一些特点

    #集合本身就像无值的字典 list1 = set([1,2,3,4]) list2 = {1,2,3,4} print('list1 == list2?:',list1==list2)#list1 = ...

  3. python学习五十五天subprocess模块的使用

    我们经常需要通过python去执行一条系统执行命令或者脚本,系统的shell命令独立于你python进程之外的,没执行一条命令,就发起一个新的进程, 三种执行命令的方法 subprocess.run( ...

  4. Python学习(五):易忘知识点

    1.列表比较函数cmp >>> a = [1,2,3,4] >>> b = [1,2,3,4,5] >>> c = [1,2,3,4] >& ...

  5. python学习心得第五章

    python学习心得第五章 1.冒泡排序: 冒泡是一种基础的算法,通过这算法可以将一堆值进行有效的排列,可以是从大到小,可以从小到大,条件是任意给出的. 冒泡的原理: 将需要比较的数(n个)有序的两个 ...

  6. python学习笔记(五岁以下儿童)深深浅浅的副本复印件,文件和文件夹

    python学习笔记(五岁以下儿童) 深拷贝-浅拷贝 浅拷贝就是对引用的拷贝(仅仅拷贝父对象) 深拷贝就是对对象的资源拷贝 普通的复制,仅仅是添加了一个指向同一个地址空间的"标签" ...

  7. Python学习笔记(五)

    Python学习笔记(五): 文件操作 另一种文件打开方式-with 作业-三级菜单高大上版 1. 知识点 能调用方法的一定是对象 涉及文件的三个过程:打开-操作-关闭 python3中一个汉字就是一 ...

  8. python学习第五次笔记

    python学习第五次笔记 列表的缺点 1.列表可以存储大量的数据类型,但是如果数据量大的话,他的查询速度比较慢. 2.列表只能按照顺序存储,数据与数据之间关联性不强 数据类型划分 数据类型:可变数据 ...

  9. Python学习第五堂课

    Python学习第五堂课推荐电影:华尔街之狼 被拯救的姜哥 阿甘正传 辛德勒的名单 肖申克的救赎 上帝之城 焦土之城 绝美之城 #上节内容: 变量 if else 注释 # ""& ...

随机推荐

  1. mac 系统安装selenium注意事项

    mac最新系统:OS X EI Captian python: 本机自带的python2.7. (本来想升级3.5,觉得太复杂,放弃了) pip: https://pypi.python.org/py ...

  2. js 获取后台数据分页

    页面创建一个存放内容的容器,以及分页的容器: <div id="content"></div> <div id="pager"&g ...

  3. zabbix-agent安装

    1.下载yum源库 rpm -i http://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm ...

  4. Dropbox的CEO在MIT的毕业演讲

    这是我今天看到的一个演讲,个人觉得和乔老大在斯坦佛的毕业演讲有异曲同工之妙,我也觉得对工科的我们很有启发意义,就此转载,希望与君共勉. 编者注:本篇文章基于Drew Houston 在 MIT 毕业典 ...

  5. 在网页中使用Markdown

    在网站中使用markdown有两种方式,一种是通过后端(php等)把markdown语法文本转换为html代码,输出到浏览器:另一种是通过javascript代码直接在浏览器中转换. 我在这里使用的是 ...

  6. 移动端web开发技巧和常见问题

    常见问题 1.移动端如何定义字体font-family 三大手机系统的字体: ios 系统 默认中文字体是Heiti SC 默认英文字体是Helvetica 默认数字字体是HelveticaNeue ...

  7. 01-Python学习笔记-基础语法

    Python标识符 -d           在解析时显示调试信息 -O           生成优化代码 ( .pyo 文件 ) -S           启动时不引入查找Python路径的位置 - ...

  8. Entity Framework中DbContext结合TransactionScope提交事务的正确方式

    问: I would like know what is the best possible way to implement transactions with DBContext. In part ...

  9. react系列(零)安装

    安装 在最初的阶段,可以使用在线编辑的网站来学习React基本的语法. 从 Hello World 开始,可以在Codepen,或者codesandbox上进行编写. 当然,也可以使用npm或者yar ...

  10. mysql获取正在运行的sql

    select id,db,host,time,info,command from information_schema.processlist where command<>'sleep' ...