Head First Python Notes - Chapter 6

class athlete:
    def __init__(self, path):
        with open(path) as timef:
            temp = timef.readline()
            temp = temp.strip().split(',')
            self.name = temp[0]
            self.date = temp[1]
            self.data = temp[2:len(temp)]
    
    def sort_time(self):
        clean_data = []
        for time in self.data:
            if '-' in time:
                splitter = '-'
            elif ':' in time:
                splitter = ':'
            else:
                splitter = '.'
            (mins, secs) = time.split(splitter)
            clean_data.append(mins + '.' + secs) 
        return sorted(set(clean_data))[0:3]
            
if __name__ == '__main__':
    james = athlete('./data/james2.txt')
    julie = athlete('./data/julie2.txt')
    mikey = athlete('./data/mikey2.txt')
    sarah = athlete('./data/sarah2.txt')
    print(james.sort_time())
    print(julie.sort_time())
    print(mikey.sort_time())
    print(sarah.sort_time())

suppose we inherit from  buildin list data type

class athlete(list):
    def __init__(self, path):
        list.__init__([])
        with open(path) as timef:
            temp = timef.readline()
            temp = temp.strip().split(',')
            self.name = temp[0]
            self.date = temp[1]
            self.extend(temp[2:len(temp)])
    
    def sort_time(self):
        clean_data = []
        for time in self:
            if '-' in time:
                splitter = '-'
            elif ':' in time:
                splitter = ':'
            else:
                splitter = '.'
            (mins, secs) = time.split(splitter)
            clean_data.append(mins + '.' + secs) 
        return sorted(set(clean_data))[0:3]
            
if __name__ == '__main__':
    james = athlete('./data/james2.txt')
    julie = athlete('./data/julie2.txt')
    mikey = athlete('./data/mikey2.txt')
    sarah = athlete('./data/sarah2.txt')
    print(james.sort_time())
    print(julie.sort_time())
    print(mikey.sort_time())
    print(sarah.sort_time()) 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值