zoukankan      html  css  js  c++  java
  • 定制数据对象2

    # Author kevin_hou
    def sanitize(time_string):  #将时间格式化为统一字符串格式
        if '-' in time_string:
            splitter = '-'
        elif ':' in time_string:
            splitter = ':'
        else:
            return(time_string)
        (mins, secs) = time_string.split(splitter)
        return(mins + '.' + secs)
    
    class Athlete:  #定义父类
        def __init__(self, a_name, a_dob=None, a_times=[]):
            self.name = a_name
            self.don = a_dob
            self.times = a_times
        def top3(self): #定义筛选前三项子函数
            return (sorted(set([sanitize(t) for t in self.times]))[0:3])
    
        def add_time(self, time_value): #将1个额外的计时值追加到选手的计时数据
            self.times.append(time_value)
    
        def add_times(self, list_of_times): #用1个或多个计时值(提供为1个列表)
            self.times.extend(list_of_times)    #来扩展1个选手的计时数据
    
    def get_coah_data(filename):    #打开文件获取数据
        try:
            with open(filename) as f:
                data = f.readline()
            temp1 = data.strip().split(',')
            # return ({'Name': temp1.pop(0),
            #          'DOB': temp1.pop(0),
            #          'Times': str(sorted(set([sanitize(t) for t in temp1]))[0:3])})
            return Athlete(temp1.pop(0), temp1.pop(0), temp1)
        except IOError as ioerr:
            print('File error:' +str(ioerr))
            return(None)
    
    james = get_coah_data('james2.txt')
    sarah = get_coah_data('sarah2.txt')
    # print(james['Name'] + "'s fastest times are:" + james['Times'])
    print(james.name + "'s fastest times are:" + str(james.top3()))
    #James Lee's fastest times are:[' 2.34', '2.01', '2.22']
    print(sarah.name + "'s fastest times are:" + str(sarah.top3()))
    #Sarah Sweeney's fastest times are:['2.18', '2.25', '2.39']
    
    vera = Athlete('Vera Vi')
    vera.add_time('1.31')
    print(vera.top3())  #['1.31']
    
    vera.add_times(['2.22', "1;21", '2:22'])
    print(vera.top3())
    

      

  • 相关阅读:
    python --异常处理
    Python -- 函数对象
    python --循环对象
    python --循环设计
    python --模块
    python --文本文件的输入输出
    xpee.vbs
    oracle 有个xe版本
    POI对Excel单元格进行颜色设置
    POI进行ExcelSheet的拷贝
  • 原文地址:https://www.cnblogs.com/kevin-hou1991/p/13680990.html
Copyright © 2011-2022 走看看