Head First Python代码实践(第六章)有注释

本文介绍了一种处理运动员数据的方法,包括数据清洗、读取和优化存储过程。通过使用Python类来组织和操作数据,提高了代码的复用性和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import os
os.chdir('./support_file')

#清洗数据
def sanitize(time_string):
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return (time_string);
    (min, secs) = time_string.split(splitter)
    return (min + '.' + secs)
'''
#将数据读到程序并转换为列表
def get_coach_data (filename):
    try:
        with open(filename) as f:
            data = f.readline()
        return (data.strip().split(','))
    except IOError as ioerr:
        print('File Err:' + str(ioerr))
        return (None)
'''
'''
#优化后的get_coach_data
def get_coach_data (filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ = data.strip().split(",")  #在一次性创建字典前创建一个临时列表存放数据
        return ({'Name':templ.pop(0),  #字典创建成为函数一部分
                  'Dob':templ.pop(0),
                  'Time':str(sorted(set(sanitize(t) for t in templ))[0:3])})  #获取前三个时间也作为函数一部分
    except IOError as ioerr:
        print('File Err:' + str(ioerr))
        return (None)

james = get_coach_data('james2.txt')
print(james['Name'] + "'s fastest times are:" + james['Time'])'''

'''#(james_name, james_dob) = james.pop(0), james.pop(0)
# print(james_name + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in james]))[0:3]))
#通过字典实现上两行
james_data = {}
james_data['Name'] = james.pop(0)
james_data['Dob'] = james.pop(0)
james_data['Time'] = james
print(james_data['Name'] + "'s fastest times are:" + str(sorted(set([sanitize(t) for t in james]))))'''



'''
#创建字典
cleese = {}
# print(type(cleese))
palin = dict()
# print(type(palin))

cleese['Name'] = 'John Cleese'
cleese['Occupations'] = ['actor', 'comedian', 'writer', 'file producer']
palin = {'Name':'Michael Palin', 'Occupations': ['comedian', 'actor', 'writer', 'tv']}
#动态添加
palin['Birthplace'] = "Broomhill, shff, England"
cleese['Birthplace'] = "Weston, North, England"
print(palin['Name'])
print(cleese['Occupations'][1])
print(palin)
print(cleese)'''

'''利用类将代码与代码处理的数据相关联(示例)
class Athlete:
    def __init__(self, a_name, a_dob = None, a_time = []):
        self.name = a_name
        self.dob = a_dob
        self.time = a_time
#创建唯一的对象实例,会继承Athlete的特性
james = Athlete('james jhons')
print(type(james))
print(james) #内存地址
print(james.name)  #点记法获得属性值'''


'''利用类对本章例子进行优化'''
class Athlete:
    def __init__(self, a_name, a_dob = None, a_time = []):
        self.name = a_name
        self.dob = a_dob
        self.time = a_time
    def top3(self):
        return (sorted(set(sanitize(t) for t in self.time))[0:3])
    ###将参数追加到现有的计时列表
    def add_time(self, time_value):
        self.time.append(time_value)
    ###用参数列表扩展现有的计时列表
    def add_time(self, list_of_time):
        self.time.extend(list_of_time)


'''
vera = Athlete('vera_vava')
print(type(vera))
vera.add_time(['0.48'])
print(vera.time)
print(vera.top3())
vera.add_time(['2.22', '1-21', '2:22'])
print(vera.time)
print(vera.top3())'''

'''继承内置list类
class NameList (list):
    def __init__(self, a_name):
        list.__init__([])
        self.name = a_name

johnny = NameList ("John Paul")
print(type(johnny))
print(dir(johnny))
print(johnny)
johnny.append("zhangsan")
johnny.extend(["lisi", 'wangwu'])
print(johnny)

for each_t in johnny:
    print(each_t)'''

'''使用继承内置list类的方式重写Athlete类'''
class AthleteList(list):
    def __init__(self, a_name, a_dob=None, a_time=[]):
        list.__init__([])
        self.name = a_name
        self.dob = a_dob
        self.extend(a_time) ###数据本身是计时数据,所以不再需要time属性
    def top3(self):
        return(sorted(set([sanitize(t) for t in self]))[0:3])

# vera = AthleteList('huluwa','2017-10')
# print(vera.dob)
# vera.append('1.01')
# print(vera.top3())


def get_coach_data (filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ = data.strip().split(",")  #在一次性创建字典前创建一个临时列表存放数据
        #return (Athlete(templ.pop(0), templ.pop(0), templ))
        return (AthleteList(templ.pop(0), templ.pop(0), templ))
    except IOError as ioerr:
        print('File Err:' + str(ioerr))
        return (None)

james = get_coach_data('james2.txt')
print(james.name + "'s fastest times are:" + str(james.top3()))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值