打包代码与数据

数据结构要与数据匹配,数据结构影响代码的复杂性
 
列表
集合
字典
#创建与初始化
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. 2018 Multi-University Training Contest 4 Problem B. Harvest of Apples 【莫队+排列组合+逆元预处理技巧】

    任意门:http://acm.hdu.edu.cn/showproblem.php?pid=6333 Problem B. Harvest of Apples Time Limit: 4000/200 ...

  2. 使用Nginx 做负载均衡

    Nginx可以作为一个非常高效的负载均衡系统,通过分发HTTP请求到多个应用服务器来提高整个系统的吞吐量,性能和可用性. 负载均衡的算法/机制 下面是Nginx支持的机制 轮询机制 轮询算法 最少连接 ...

  3. Nginx 作为静态资源服务器

    Nginx Windows 版本的启动停止,重新加载配置 启动 Windows版本下载解压后有一个nginx.exe可执行文件,双击启动. 启动后 浏览器访问http://127.0.0.1 可以看到 ...

  4. 提示AttributeError: 'module' object has no attribute 'HTTPSHandler'解决方法

    今天在新机器上安装sqlmap,运行提示AttributeError: 'module' object has no attribute 'HTTPSHandler' 网上找了找资料,发现一篇文章ht ...

  5. oracle表空间的创建+权限分配

    /*分为四步 */ /*第1步:创建临时表空间 */ create temporary tablespace user_temp tempfile 'D:\oracle\oradata\Oracle9 ...

  6. Objective-C 中的 assign, copy,retain,strong,weak 详解

    在IOS开发中,经常会使用   @property(nonatomic,copy)NSString * name;   语句来快速设置set get 方法,在此依次说明atomic .nonatomi ...

  7. python 面向对象之添加功能

    '''**#实现功能**案列 姓名:王飞 年龄:30 性别:男 工龄:5我承诺,我会认真教课.王飞爱玩象棋 姓名:小明 年龄:15 性别:男 学号:00023102我承诺,我会 好好学习.小明爱玩足球 ...

  8. SHELL脚本简单的赋值与递增

    Count=`expr $Count + 1`;#可以在各种shell执行,其他类C的写法只能在指定的bash版本执行; 赋值不能带$, 带$相当于字符串常量了;执行脚本参考如下 #!/bin/sh ...

  9. ABAP术语-qRFC-Monitor

    qRFC-Monitor 原文:http://www.cnblogs.com/qiangsheng/archive/2008/03/10/1098543.html Central monitoring ...

  10. JQuery制作网页—— 第六章 jQuery选择器

    1.jQuery选择器:jQuery选择器类似于CSS选择器,用来选取网页中的元素.       Eg:$("h3").css("background",&qu ...