打包代码与数据

数据结构要与数据匹配,数据结构影响代码的复杂性
 
列表
集合
字典
#创建与初始化
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. VGG使用重复元素的网络

    由5个卷积层块(2个单卷积层,3个双卷积层),3个全连接层组成——VGG-11 from mxnet import gluon,init,nd,autograd from mxnet.gluon im ...

  2. _bstr_t可接受多字节、UNICODE字符串,方便用以字符集转换

    使用_bstr_t需要包含的头文件: #include <comutil.h> #include <comdef.h> // test.cpp : 定义控制台应用程序的入口点. ...

  3. php模板引擎的原理与简单实例

    模板引擎其实就是将一个带有自定义标签的字符串,通过相应的规则解析,返回php可以解析的字符串,这其中正则的运用是必不可少的,所以要有一定的正则基础.总体思想,引入按规则写好的模板,传递给标签解析类(_ ...

  4. zabbix安装(网络)

    https://www.zabbix.com/documentation/3.4/zh/manual/quickstart/login   zabbix安装官网 https://www.zabbix. ...

  5. event对象,ie8及其以下

    event 对象是 JavaScript 中一个非常重要的对象,用来表示当前事件.event 对象的属性和方法包含了当前事件的状态.当前事件,是指正在发生的事件:状态,是与事件有关的性质,如引发事件的 ...

  6. 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件

    “/”应用程序中的服务器错误. 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件“c552ea94-6fbb-11d5-a9c1-00104bb6fc1c”. 说明: 执行当前 Web ...

  7. HDU 1250 Hat's Fibonacci(大数相加)

    传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1250 Hat's Fibonacci Time Limit: 2000/1000 MS (Java/Ot ...

  8. IE下页面左偏移并页头空出一行解决方法

    在其它浏览器下显示正常,包括360浏览器,在IE下,页面向左偏移,通过firebug查看,head标签为空,并且head标签里面的内容都跑到body标签内了,原因是有bom头,访问的页面或是加载,包含 ...

  9. Web项目开发中常见安全问题及防范

    计算机程序主要就是输入数据 经过处理之后 输出结果,安全问题由此产生,凡是有输入的地方都可能带来安全风险.根据输入的数据类型,Web应用主要有数值型.字符型.文件型. 要消除风险就要对输入的数据进行检 ...

  10. Web—06-JavaScript

    JavaScript介绍 JavaScript是运行在浏览器端的脚步语言,JavaScript主要解决的是前端与用户交互的问题,包括使用交互与数据交互. JavaScript是浏览器解释执行的,前端脚 ...