打包代码与数据

数据结构要与数据匹配,数据结构影响代码的复杂性
 
列表
集合
字典
#创建与初始化
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. mvc读书笔记

    在mvc3的時候引入了Razor.Mvc4中默認的頂級目錄/controllers 保存那些處理URL請求的controller類/models 保存那些表示和操縱數據以及業務對象的類/views 保 ...

  2. angular.js和ionic框架搭建一个webApp

    原文地址:http://www.jianshu.com/p/ea0dcf1d31c9

  3. 如何安装zip格式的MySQL

    1.MySQL安装文件分为两种,一种是msi格式的,一种是zip格式的.如果是msi格式的可以直接点击安装,按照它给出的安装提示进行安装(相信大家的英文可以看懂英文提示),一般MySQL将会安装在C: ...

  4. HDU 1012 u Calculate e(简单阶乘计算)

    传送门: http://acm.hdu.edu.cn/showproblem.php?pid=1012 u Calculate e Time Limit: 2000/1000 MS (Java/Oth ...

  5. 【转载】iPhone屏幕尺寸、分辨率及适配

    iPhone屏幕尺寸.分辨率及适配 转载http://m.blog.csdn.net/article/details?id=42174937 1.iPhone尺寸规格 iPhone 整机宽度Width ...

  6. 用javascript编写简单银行取钱存钱流程(函数)

    const readline = require('readline-sync')//引用readline-sync let arr = [[], []]; //登陆 let add = functi ...

  7. Intermediate_JVM 20180306 : 运行时数据区域

    Java比起C++一个很大的进步就在于Java不用再手动控制指针的delete与free,统一交由JVM管理,但也正因为如此,一旦出现内存溢出异常,不了解JVM,那么排查问题将会变成一项艰难的工作. ...

  8. C++笔记006:关于类的补充

    原创笔记,转载请注明出处! 点击[关注],关注也是一种美德~ 关于类的补充: 类是一个数据类型(固定大小内存块的别名),定义一个类,是一个抽象的概念,不会给你分配内存,用数据类型定义变量的时候,才会分 ...

  9. JFinal DB.tx()事务回滚及lambda表达式应用

    JFinal DB.tx()事务回滚 在要往数据库操作多条数据时,就需要用到事务,JFinal中有封装好的事务应用 写法: Db.tx(new IAtom(){ @Override public bo ...

  10. LogViewer超大文本浏览工具

    官方下载 LogViewer 是一款简单好用的log日志文件查看工具.您想要查看log日志吗?那么不妨来看看这款LogViewer .该款工具可以在短短数秒内打开上G的LOG文件,支持高亮某行文字(例 ...