• python学习五


    打包代码与数据

    数据结构要与数据匹配,数据结构影响代码的复杂性
     
    列表
    集合
    字典
    #创建与初始化
    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()))
  • 相关阅读:
    cygwin下安装scws
    atitit.提升软件开发的生产力关健点-------大型开发工具最关健
    atitit。mssql sql server 转换mysql 及 分页sql ast的搭建
    atitit.手动配置列表文件的选择and 数据的层次结构 attilax总结最佳实践--yaml
    atitit.获取connection hibernate4
    atitit.新增编辑功能 跟orm的实现 attilax p31
    atitit.自动生成数据库结构脚本,或者更换数据库,基于hibernate4
    atitit.Windows Server 2003 2008 2012系统的新特性 attilax 总结
    atitit.orm的缺点与orm框架市场占有率,选型attilax总结
    atitit。解决 No suitable Log constructor。。NoClassDefFoundError: org/apache/log4j/Category 找不到类的
  • 原文地址:https://www.cnblogs.com/manziluo/p/5800228.html
Copyright © 2020-2023  润新知