打包代码与数据

数据结构要与数据匹配,数据结构影响代码的复杂性
 
列表
集合
字典
#创建与初始化
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. [19/04/05-星期五] 多线程_Thread(线程、线条)、基本术语

    一.基本概念 多线程是Java语言的重要特性,大量应用于网络编程.服务器端程序的开发,最常见的UI界面底层原理.操作系统底层原理都大量使用了多线程. 我们可以流畅的点击软件或者游戏中的各种按钮,其实, ...

  2. 21、整合Druid数据源

    1).引入外部的数据源(Druid) <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependenc ...

  3. linux如何安装IntelliJ IDEA

    http://www.linuxidc.com/Linux/2016-12/137946.htm 创建的那个启动器脚本,只要这样输入就可以直接启动idea了

  4. 论文笔记 | A Closer Look at Spatiotemporal Convolutions for Action Recognition

    ( 这篇博文为原创,如需转载本文请email我: leizhao.mail@qq.com, 并注明来源链接,THX!) 本文主要分享了一篇来自CVPR 2018的论文,A Closer Look at ...

  5. ConcurrentHashMap 中putIfAbsent 和put的区别

    putIfAbsent 源代码 public V putIfAbsent(K key, V value) { Segment<K,V> s; if (value == null) thro ...

  6. Objective-C——消息、Category和Protocol

    转自:http://www.cnblogs.com/chijianqiang/archive/2012/06/22/objc-category-protocol.html 面向对象永远是个可以吐槽的话 ...

  7. 智能指针 与 oc中的指针

     智能指针 与 oc中的指针 智能指针的原理及实现 当类中有指针成员时,一般有两种方式来管理指针成员:一是采用值型的方式管理,每个类对象都保留一份指针指向的对象的拷贝:另一种更优雅的方式是使用智能指针 ...

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

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

  9. 19-3-4 Python进制转换;bool str int三者之间的转换;字符串的索引,切片;for循环的使用

    进制转换: 二进制转十进制:  0010 1111 = 1*2**0+1*2**1+1*2**2+1*2**3+1*2**5 十进制转换二进制: 用十进制数除2逆序取余 --->101010 布 ...

  10. 解决微信小程序安卓手机访问不到图片,无法显示图片

    关于微信小程序不显示图片 通病可能有以下几个可能性: 非本地图片:确定图片资源存在,copy 图片url再浏览器打开,确定图片资源存在且能正常访问 本地图片:确定相对路径或者绝对路径正确 微信小程序图 ...